image: shiplogic/ci-wp-plugin:node18

variables:
  GIT_SUBMODULE_STRATEGY: recursive
  MAX_TAGS_TO_KEEP: 5

stages:
  - deploy
  - tag_deploy

deploy:
  stage: deploy
  before_script:
    - AWS_ACCESS_KEY_ID_KEY=$(echo "$CI_COMMIT_BRANCH"_"AWS_ACCESS_KEY_ID")
    - AWS_ACCESS_KEY_ID=$(eval echo -e "\$$AWS_ACCESS_KEY_ID_KEY")
    - AWS_SECRET_ACCESS_KEY_KEY=$(echo "$CI_COMMIT_BRANCH"_"AWS_SECRET_ACCESS_KEY")
    - AWS_SECRET_ACCESS_KEY=$(eval echo -e "\$$AWS_SECRET_ACCESS_KEY_KEY")
    - export AWS_ACCESS_KEY_ID
    - export AWS_SECRET_ACCESS_KEY
  script:
    - ./make-zip.sh
    - aws s3 cp bobgo-magento-plugin.zip s3://bobgo-s3-magento-plugin-dev/ --region=af-south-1
  rules:
    - if: $CI_COMMIT_BRANCH == "dev" && $CI_PIPELINE_SOURCE == "push"
      when: always

tag_deploy:
  stage: tag_deploy
  before_script:
    - AWS_ACCESS_KEY_ID_KEY="prod_AWS_ACCESS_KEY_ID"
    - AWS_SECRET_ACCESS_KEY_KEY="prod_AWS_SECRET_ACCESS_KEY"
    - AWS_ACCESS_KEY_ID=$(eval echo -e "\$$AWS_ACCESS_KEY_ID_KEY")
    - AWS_SECRET_ACCESS_KEY=$(eval echo -e "\$$AWS_SECRET_ACCESS_KEY_KEY")
    - export AWS_ACCESS_KEY_ID
    - export AWS_SECRET_ACCESS_KEY
    - git fetch origin prod
    - COMMIT_BRANCH=$(git branch -r --contains $CI_COMMIT_SHA | grep "origin/prod" || echo "")
    - if [ -z "$COMMIT_BRANCH" ]; then echo "Tag was not created from prod branch. Skipping deployment."; exit 1; fi
  script:
    - "TAG_ARCHIVE_URL=https://gitlab.bob.co.za/bob-public-utils/bobgo-magento-extension/-/archive/${CI_COMMIT_TAG}/bobgo-magento-extension-${CI_COMMIT_TAG}.zip"
    - curl -o bobgo-magento-extension-${CI_COMMIT_TAG}.zip "$TAG_ARCHIVE_URL"
    - aws s3 cp bobgo-magento-extension-${CI_COMMIT_TAG}.zip s3://bobgo-s3-magento-plugin-prod/tags/bobgo-magento-extension-${CI_COMMIT_TAG}.zip --region=af-south-1 --acl public-read
    - aws s3 cp bobgo-magento-extension-${CI_COMMIT_TAG}.zip s3://bobgo-s3-magento-plugin-prod/latest/bobgo-magento-extension-latest.zip --region=af-south-1 --acl public-read
    - echo "Tagged version URL in S3 bucket ready for download"
  rules:
    - if: $CI_COMMIT_TAG
      when: always