image: node:20

pipelines:
  branches:
    main:
      - step:
          name: Build and Setup
          script:
            - echo 'Build Success'

      - step:
          name: Build & Push to ECR
          services:
            - docker
          script:
            - apt-get update
            - apt-get install -y awscli
            - aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
            - aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY
            - echo 'Logging in to ECR...'
            - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
            - docker build --build-arg AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID --build-arg AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY -t $APPLICATION_NAME .
            - docker tag $APPLICATION_NAME:latest $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$APPLICATION_NAME:latest
            - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$APPLICATION_NAME:latest

      - step:
          name: ECS restart Service
          script:
            - apt-get update
            - apt-get install -y awscli
            - aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
            - aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY
            - aws ecs update-service --cluster $ECS_CLUSTER_NAME --service $ECS_SERVICE_NAME --desired-count 1 --force-new-deployment
            - echo 'service stop success'
      
