stages:
  - quality_check
  - build
  - push_tag
  - deploy_staging
  - deploy_production

variables:
  NAMESPACE: "default"
  REGISTRY_GCP: europe-west1-docker.pkg.dev/ops-shared-e3afff9d/gitlab-pipeline
  IMAGE_NAME: "${REGISTRY_GCP}/${APPLICATION_NAME}"
  RELEASE_NAME: ${APPLICATION_NAME}
  CHART_DIR: helm-chart
  CI_TEMPLATES_GIT_USER: pipeline-git-ro
  CI_TEMPLATES_GIT_PROJECT_URL: gitlab.com/finboot/it-operations/ci-templates.git
  CI_TEMPLATES_GIT_PASSWORD: gphEDJxZScK9cC9qUdE3
  GKE_REGION: europe-west1
  SONAR_ENDPOINT: ${SONAR_ENDPOINT}
  SONAR_TOKEN: ${SONAR_TOKEN}

quality_check:
  image: europe-west1-docker.pkg.dev/ops-shared-e3afff9d/sync-images/sonarsource/sonar-scanner-cli:stable
  stage: quality_check
  tags:
    - docker
  script:
    - apk add --update bash git curl gettext nodejs npm
    - git clone https://${CI_TEMPLATES_GIT_USER}:${CI_TEMPLATES_GIT_PASSWORD}@${CI_TEMPLATES_GIT_PROJECT_URL}
    - cd ci-templates
    - scripts/notify-slack-start-pipeline.sh
    - cd ../
    - TAG_VERSION=$(node -p "require('./package.json').version" 2>/dev/null || echo "0.0.0")
    - echo TAG_VERSION=${TAG_VERSION}
    - TAG_IMAGE=${TAG_VERSION}-${CI_COMMIT_SHORT_SHA}
    - echo "${TAG_IMAGE}" > tag-image
    - cat Dockerfile | envsubst > Dockerfile_LOAD
    - >
      sonar-scanner
      -Dsonar.projectKey=${APPLICATION_NAME}
      -Dsonar.projectVersion=${TAG_VERSION}
      -Dsonar.host.url=${SONAR_ENDPOINT}
      -Dsonar.login=${SONAR_TOKEN}
      -Dsonar.scm.provider=git
      -Dsonar.qualitygate.wait=true
      -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info
  allow_failure: false
  artifacts:
    paths:
      - tag-image
      - Dockerfile_LOAD
  only:
    - /^feature\/.*$/
    - /^hotfix\/.*$/
    - master
    - main

push_tag:
  stage: push_tag
  tags:
    - docker
  image: europe-west1-docker.pkg.dev/ops-shared-e3afff9d/sync-images/finboot-custom/docker-git:stable
  script:
    - TAG_IMAGE=$(cat tag-image)
    # CREATE TAG
    - git config user.email "${GITLAB_USER_EMAIL}"
    - git config user.name "${GITLAB_USER_NAME}"
    - echo "Debug gitlab.com/${CI_PROJECT_PATH}"
    - git tag
    - git remote set-url origin https://oauth2:${GITLAB_ACCESS_TOKEN}@gitlab.com/${CI_PROJECT_PATH}
    # Check if not exist this tag
    - |
      if git rev-parse "${TAG_IMAGE}" >/dev/null 2>&1;
      then
        echo "Tag Version $VERSION already exists"
      else
        git tag -a "${TAG_IMAGE}" -m "Version created by gitlab-ci Build"
        git push origin "${TAG_IMAGE}"
      fi
  allow_failure: false # Mandatory be success to continue
  artifacts:
    paths:
      - tag-image
  only:
    - /^feature\/.*$/
    - /^hotfix\/.*$/
    - master
    - main

.build:
  stage: build
  tags:
    - docker
  image: europe-west1-docker.pkg.dev/ops-shared-e3afff9d/sync-images/finboot-custom/docker-git:stable
  script:
    - apk add --update bash git curl gettext nodejs npm
    - git clone https://${CI_TEMPLATES_GIT_USER}:${CI_TEMPLATES_GIT_PASSWORD}@${CI_TEMPLATES_GIT_PROJECT_URL}
    - cd ci-templates
    - scripts/notify-slack-start-pipeline.sh
    - cd ../
    - TAG_VERSION=$(node -p "require('./package.json').version" 2>/dev/null || echo "0.0.0")
    - echo TAG_VERSION=${TAG_VERSION}
    - echo MARCO_API_PARENT_URL = ${MARCO_API_PARENT_URL}
    #- TAG_IMAGE=$(echo ${TAG} | sed 's/\//-/g;s/_/-/g')
    - TAG_IMAGE=${TAG_VERSION}-${CI_COMMIT_SHORT_SHA}
    - echo TAG_IMAGE=${TAG_IMAGE}
    - cat Dockerfile | envsubst > Dockerfile_LOAD | docker build --no-cache -t "${IMAGE_NAME}:${TAG_IMAGE}" -f Dockerfile_LOAD .
    - docker login -u _json_key -p "$SA_GCR" https://europe-west1-docker.pkg.dev
    - docker push "${IMAGE_NAME}:${TAG_IMAGE}"
    - echo Image uploaded "${IMAGE_NAME}:${TAG_IMAGE}"
    - echo "${TAG_IMAGE}" > tag-image
    # CREATE TAG
    - git config user.email "${GITLAB_USER_EMAIL}"
    - git config user.name "${GITLAB_USER_NAME}"
    - echo "Debug gitlab.com/${CI_PROJECT_PATH}"
    - git tag
    - git remote set-url origin https://oauth2:${GITLAB_ACCESS_TOKEN}@gitlab.com/${CI_PROJECT_PATH}
    # Check if not exist this tag
    - |
      if git rev-parse "${TAG_IMAGE}" >/dev/null 2>&1;
      then
        echo "Tag Version $VERSION already exists"
      else
        git tag -a "${TAG_IMAGE}" -m "Version created by gitlab-ci Build"
        git push origin "${TAG_IMAGE}"
      fi
  artifacts:
    paths:
      - tag-image

.build_test_staging_main:
  stage: build
  extends: .build
  environment:
    name: staging
  variables:
    MARCO_API_PARENT_URL: https://api-marco.finboot-test.com
  only:
    - /^feature\/.*$/
    - /^hotfix\/.*$/
  except:
    - master
    - main

.build_test_production_main:
  stage: build
  extends: .build
  variables:
    MARCO_API_PARENT_URL: https://api-marco.finboot.com
  environment:
    name: production
  only:
    - master
    - main

.deployment_script:
  tags:
    - docker
  image:
    name: europe-west1-docker.pkg.dev/ops-shared-e3afff9d/sync-images/finboot-custom/gitlab-job-deploy:stable
  before_script:
    - mkdir -p /etc/deploy
    - echo ${SA_GKE} | base64 -d | base64 -d > /etc/deploy/sa.json
    - gcloud auth activate-service-account --key-file /etc/deploy/sa.json --project=${GKE_PROJECT}
    - gcloud container clusters get-credentials ${GKE_CLUSTER_NAME} --zone ${GKE_REGION} --project ${GKE_PROJECT}
    - echo $SA_GCR >> .google_credentials.json
    - export GOOGLE_APPLICATION_CREDENTIALS=.google_credentials.json
    - gcloud auth application-default print-access-token | helm registry login -u oauth2accesstoken --password-stdin https://europe-southwest1-docker.pkg.dev
  script:
    - git clone https://${CI_TEMPLATES_GIT_USER}:${CI_TEMPLATES_GIT_PASSWORD}@${CI_TEMPLATES_GIT_PROJECT_URL}
    - IMAGE_VERSION=$(cat tag-image)
    - cd ci-templates
    - scripts/deploy/deploy-template.sh "${IMAGE_VERSION}"
  artifacts:
    paths:
      - tag-image
  timeout: 10m

.deploy_staging_main:
  extends: .deployment_script
  variables:
    SA_GKE: ${SA_GKE_STAGE}
    GKE_PROJECT: ${STAGE_GKE_PROJECT}
    GKE_CLUSTER_NAME: ${STAGE_GKE_CLUSTER_NAME}
    STACK: stage
    HEALTHCHECK: ${STAGE_HEALTHCHECK}
    HEALTHCHECK_MARCO_APPLICATION_TOKEN: ${STAGE_HEALTHCHECK_MARCO_APPLICATION_TOKEN}
  environment:
    name: staging
    url: https://${APPLICATION_NAME}.finboot-test.com
  rules:
    - if: '$CI_MERGE_REQUEST_EVENT_TYPE == "detached"'
      # Avoid creating additional pipeline when in merge requests
      when: never
    - if: '$CI_COMMIT_REF_SLUG =~ /^(feature|hotfix)/'
      when: manual # Force manual deploy for merge requests
      allow_failure: true
    - if: '$CI_COMMIT_REF_SLUG == $CI_DEFAULT_BRANCH' # Auto deploy on default branch
      when: on_success

.deploy_production_main:
  extends: .deployment_script
  variables:
    SA_GKE: ${SA_GKE_PROD}
    GKE_PROJECT: ${PROD_GKE_PROJECT}
    GKE_CLUSTER_NAME: ${PROD_GKE_CLUSTER_NAME}
    STACK: prod
    HEALTHCHECK: ${PROD_HEALTHCHECK}
    HEALTHCHECK_MARCO_APPLICATION_TOKEN: ${PROD_HEALTHCHECK_MARCO_APPLICATION_TOKEN}
  environment:
    name: production
    url: https://${APPLICATION_NAME}.finboot.com
  needs: ["deploy_staging"] # It needs staging working
  when: manual
  only:
    - master
    - main
