version: 0.2

phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - eval $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
      - REPOSITORY_URI=${ecr_address}
      - GITHUB_TOKEN=${gh_token}
      - IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - git config --global credential.helper store
      - printf "https://$GITHUB_TOKEN:x-oauth-basic@github.com\n" >> /root/.git-credentials
      - git config --global user.email "builder@example.com"
      - git config --global user.name "AWS CICD"
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
#      - git init 
#      - git submodule update --recursive --remote     
      - git clone https://github.com/somecompany/erlangservice.git
      - docker pull $IMAGE_REPO_NAME:latest || true    
      - docker build --build-arg POSTGRES_USERNAME=${db_user} --build-arg POSTGRES_HOST=${db_host} --build-arg POSTGRES_PASSWORD=${db_pass} --build-arg POSTGRES_DB=${db_name} --cache-from $CONTAINER_REPOSITORY_URL:latest -t $IMAGE_REPO_NAME:latest .
      - docker tag $IMAGE_REPO_NAME:latest $IMAGE_REPO_NAME:$IMAGE_TAG
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $IMAGE_REPO_NAME:latest
      - docker push $IMAGE_REPO_NAME:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"${task_name}","imageUri":"%s"}]' $IMAGE_REPO_NAME:$IMAGE_TAG > imagedefinitions.json
artifacts:
    files: imagedefinitions.json