stages:
    - build
    - deploy-preprod
    - deploy-prod

build-docker:
    stage: build
    image: docker:20.10.16
    services:
        - name: docker:20.10.16-dind
          alias: docker
    before_script:
        - docker info
    script:
        - |
          if [ "$CI_COMMIT_REF_NAME" == "production" ]; then
            export TAG="latest"
          elif [ "$CI_COMMIT_REF_NAME" == "Preprod" ]; then
            export TAG="preprod-latest"
          else
            export TAG="${CI_COMMIT_REF_NAME}-latest"
          fi
        - echo "Building Docker image with tag $TAG"
        - docker build . -t registry.gitlab.com/fstck/urban-canopee/urban-canopee-api:$TAG -t registry.gitlab.com/fstck/urban-canopee/urban-canopee-api:$CI_COMMIT_SHA
        - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN registry.gitlab.com
        - docker image push registry.gitlab.com/fstck/urban-canopee/urban-canopee-api:$TAG
        - docker image push registry.gitlab.com/fstck/urban-canopee/urban-canopee-api:$CI_COMMIT_SHA

deploy-preprod:
  stage: deploy-preprod
  image: alpine:latest
  needs:
    - build-docker
  only:
    - Preprod
  before_script:
    - 'command -v ssh-agent > /dev/null || (apk add --update openssh)'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $PREPROD_SERVER_FQDN >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
  script:
    - ssh debian@$PREPROD_SERVER_FQDN "cd /home/debian/uc-api && docker compose pull && docker compose up -d"

deploy-prod:
  stage: deploy-prod
  image: alpine:latest
  needs:
    - build-docker
  only:
    - production
  before_script:
    - 'command -v ssh-agent > /dev/null || (apk add --update openssh)'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan -p55248 $PROD_SERVER_FQDN >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
  script:
    - ssh -p55248 root@$PROD_SERVER_FQDN "cd /opt/services/urban-canopee-api-docker && docker compose pull && docker compose up -d"
