version: 2
jobs:
  build:
    docker:
      - image: 204113847067.dkr.ecr.eu-central-1.amazonaws.com/circleci-build-agent:latest
        aws_auth:
          aws_access_key_id: $AWS_ACCESS_KEY_ID
          aws_secret_access_key: $AWS_SECRET_ACCESS_KEY
    steps:
      # Add the deploy key in order to be able to clone from Bitbucket.
      - add_ssh_keys
      - checkout
      - setup_remote_docker
      - run:
          name: "Clone repository into .docker"
          command: |
            cd .docker
            git clone -b $CIRCLE_BRANCH --single-branch git@github.com:Mobinet113/broffe.com-docker.git
      - run:
          name: "Replace placeholders in wp-config.php"
          command: |
            sed -i -e "s/{{ENVIRONMENT}}/${CIRCLE_BRANCH}/" .docker/wp-config.php.dist
            sed -i -e 's/{{DB_NAME}}/covarius/' .docker/wp-config.php.dist
            sed -i -e 's/{{DB_USER}}/covarius/' .docker/wp-config.php.dist
            sed -i -e "s/{{DB_PASSWORD}}/${DB_PASSWORD}/" .docker/wp-config.php.dist
      - run:
          name: "Replace placeholders in metricbeat.yml and filebeat.yml"
          command: |
            sed -i -e "s/{{BRANCH}}/${CIRCLE_BRANCH}/" .docker/filebeat.yml
            sed -i -e "s/{{BRANCH}}/${CIRCLE_BRANCH}/" .docker/metricbeat.yml
      - run:
          name: "Authenticate with AWS"
          command: eval $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
      - run:
          name: "Build and push the docker image"
          command: |
            cd .docker
            docker build -t 204113847067.dkr.ecr.eu-central-1.amazonaws.com/covarius:${CIRCLE_BRANCH} .
            docker push 204113847067.dkr.ecr.eu-central-1.amazonaws.com/covarius:${CIRCLE_BRANCH}
  deploy:
    docker:
      - image: 204113847067.dkr.ecr.eu-central-1.amazonaws.com/circleci-deploy-agent:latest
        aws_auth:
          aws_access_key_id: $AWS_ACCESS_KEY_ID
          aws_secret_access_key: $AWS_SECRET_ACCESS_KEY
    steps:
      # Add the deploy key in order to be able to clone from Bitbucket.
      - add_ssh_keys
      - checkout
      - run:
          name: "Clone deployment scripts"
          command: |
            mkdir scripts
            cd scripts
            git clone -b develop --single-branch git@bitbucket.org:silveragency/circleci-scripts.git .
      - run:
          name: "npm install"
          command: |
            cd scripts
            npm install
      - run:
          name: "Deploy to AWS"
          command: |
            cd scripts
            node setup.js
            node tasks.js
            node alb.js
            node services.js

workflows:
  version: 2
  build-deploy:
    jobs:
      - build
      - deploy:
          requires:
            - build
          filters:
            branches:
              ignore:
                - develop
                - master
                - stage
