version: 0.2

environment:
  variables:
    AWS_MAX_ATTEMPTS: 10
    AWS_RETRY_MODE: standard

phases:
  install:
    #runtime-versions:
      #docker: latest
    commands:
      - apt update
      - apt-get install jq -y
      - curl -O https://bootstrap.pypa.io/get-pip.py
      - python get-pip.py --user
      - pip3 install awscli --upgrade --user
      #- pip3 install boto3 --user
      - pip3 install botocore==1.33.2 s3transfer==0.8.1 boto3==1.33.2
      #- python3 -m venv venv
      #- source venv/bin/activate
      #- pip3 install awscli

  build:
    commands:
      - prevBuildNumber=$(aws codebuild batch-get-builds --ids $(echo $(aws codebuild list-builds-for-project --project-name $codebuild_project_name --max-items 2 | jq -r '.ids[1]')) | jq -r '.builds[0].buildNumber')
      - cd www/
      - mv js/custom-template.js js/custom.js
      - sed -i "s/{{domain_name}}/$domain/g" js/custom.js

      - sed -i "s/{{domain_name}}/$domain/g" js/custom.js
      - sed -i "s/{{build_number}}/$CODEBUILD_BUILD_NUMBER/g" js/custom.js
      - sed -i "s/{{s3_bucket_name}}/$s3_bucket_name/g" js/custom.js
      - cd ..
      - python replace.py
      - cd www/
      - tail -20 index.html
      - aws s3 cp --recursive ./ s3://$app_s3_bucket_name/ --exclude "*/*" --include "./*.html" --cli-connect-timeout 0 --cli-read-timeout 0 #MOVE HTML FILES
      - aws s3 cp --recursive ./theme s3://$app_s3_bucket_name/${CODEBUILD_BUILD_NUMBER}theme  --cli-connect-timeout 0 --cli-read-timeout 0
      - aws s3 cp --recursive ./frontend s3://$app_s3_bucket_name/${CODEBUILD_BUILD_NUMBER}frontend  --cli-connect-timeout 0 --cli-read-timeout 0
      - aws s3 cp --recursive ./js s3://$app_s3_bucket_name/${CODEBUILD_BUILD_NUMBER}js  --cli-connect-timeout 0 --cli-read-timeout 0

      #Nockies specific - To be only in MASTER branch
      - aws s3 cp --recursive ./theme s3://${app_s3_bucket_name}-nockies/${CODEBUILD_BUILD_NUMBER}theme  --cli-connect-timeout 0 --cli-read-timeout 0
      - aws s3 cp --recursive ./frontend s3://${app_s3_bucket_name}-nockies/${CODEBUILD_BUILD_NUMBER}frontend  --cli-connect-timeout 0 --cli-read-timeout 0
      - aws s3 cp --recursive ./js s3://${app_s3_bucket_name}-nockies/${CODEBUILD_BUILD_NUMBER}js  --cli-connect-timeout 0 --cli-read-timeout 0

      #- aws s3 rm --recursive s3://$app_s3_bucket_name/${prevBuildNumber}js
      #- aws s3 rm --recursive s3://$app_s3_bucket_name/${prevBuildNumber}theme
      #- aws s3 rm --recursive s3://$app_s3_bucket_name/${prevBuildNumber}frontend
      - cd ..
      - python cf-invalidation.py
      - aws codepipeline start-pipeline-execution --name ${codepipeline_be}
