import jenkins.model.Jenkins
import javaposse.jobdsl.dsl.helpers.*
import javaposse.jobdsl.dsl.helpers.step.*

proxy = Jenkins.getInstance().proxy

StepContext.metaClass.uploadBeanstalkApp = { String app, String filename ->
  shell """
set +x
export AWS_ACCESS_KEY_ID=\$AWS_ACCESS_KEY
export AWS_SECRET_ACCESS_KEY=\$AWS_SECRET_KEY
export AWS_DEFAULT_REGION='us-west-2'
aws s3 cp ${filename} s3://elastic-beanstalk-docker/${app}/\$GIT_COMMIT.zip
aws elasticbeanstalk create-application-version --no-auto-create-application --application-name ${app} --version-label \${GIT_COMMIT} --source-bundle S3Bucket=elastic-beanstalk-docker,S3Key=${app}/\$GIT_COMMIT.zip
"""
}

StepContext.metaClass.deployBeanstalkApp = { String app ->
  shell """
set +x
pip install awsebcli >/dev/null
export AWS_ACCESS_KEY_ID=\$AWS_ACCESS_KEY
export AWS_SECRET_ACCESS_KEY=\$AWS_SECRET_KEY
export AWS_DEFAULT_REGION='us-west-2'
mkdir .elasticbeanstalk
cat > .elasticbeanstalk/config.yml <<EOF
global:
  application_name: ${app}
  default_region: us-west-2
EOF
eb deploy \$ENVIRONMENT --version \$GIT_COMMIT
"""
}

job {
  name "d8a-clio"
  using 'TEMPLATE-autobuild'
  scm {
    git {
      remote {
        github 'd8a/clio', 'ssh', 'git-aws.internal.justin.tv'
                credentials 'git-aws-read-key'
      }
            clean true
    }
  }

  wrappers {
        credentialsBinding {
            string 'AWS_ACCESS_KEY', 'jenkins-terraform-aws-access-key'
            string 'AWS_SECRET_KEY', 'jenkins-terraform-aws-secret-key'
        }
    }

  steps {
    shell 'scripts/app_build.sh d8a/clio \$GIT_COMMIT'
    uploadBeanstalkApp 'clio', 'app.zip'
  }
}

job {
  name 'd8a-clio-deploy'
  using 'TEMPLATE-deploy'

    wrappers {
        credentialsBinding {
            string 'AWS_ACCESS_KEY', 'jenkins-terraform-aws-access-key'
            string 'AWS_SECRET_KEY', 'jenkins-terraform-aws-secret-key'
        }
    }

  steps {
    deployBeanstalkApp 'clio'
  }
}