stages:
  - build
  - deploy

variables:
  DOCKER_DRIVER: overlay2
  DOCKER_TLS_CERTDIR: "/certs"

build:prometheus:
  stage: build
  image: docker:24.0.5
  services:
    - docker:24.0.5-dind
  script:
    - cd apm/prometheus
    - docker build -t $CI_REGISTRY_IMAGE/prometheus:$CI_COMMIT_SHORT_SHA .
    - docker tag $CI_REGISTRY_IMAGE/prometheus:$CI_COMMIT_SHORT_SHA $CI_REGISTRY_IMAGE/prometheus:latest
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker push $CI_REGISTRY_IMAGE/prometheus:$CI_COMMIT_SHORT_SHA
    - docker push $CI_REGISTRY_IMAGE/prometheus:latest
  only:
    changes:
      - apm/prometheus/**/*
    refs:
      - main
      - dev_*

build:grafana:
  stage: build
  image: docker:24.0.5
  services:
    - docker:24.0.5-dind
  script:
    - cd apm/grafana
    - docker build -t $CI_REGISTRY_IMAGE/grafana:$CI_COMMIT_SHORT_SHA .
    - docker tag $CI_REGISTRY_IMAGE/grafana:$CI_COMMIT_SHORT_SHA $CI_REGISTRY_IMAGE/grafana:latest
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker push $CI_REGISTRY_IMAGE/grafana:$CI_COMMIT_SHORT_SHA
    - docker push $CI_REGISTRY_IMAGE/grafana:latest
  only:
    changes:
      - apm/grafana/**/*
    refs:
      - main
      - dev_*

deploy:dev:
  stage: deploy
  image: alpine:latest
  before_script:
    - apk add --no-cache openssh-client
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $DEV_SERVER_HOST >> ~/.ssh/known_hosts
  script:
    - ssh $DEV_SERVER_USER@$DEV_SERVER_HOST "cd /opt/hellotax/apm && docker-compose pull && docker-compose up -d"
  only:
    refs:
      - dev_*
  when: manual

deploy:prod:
  stage: deploy
  image: alpine:latest
  before_script:
    - apk add --no-cache openssh-client
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $PROD_SERVER_HOST >> ~/.ssh/known_hosts
  script:
    - ssh $PROD_SERVER_USER@$PROD_SERVER_HOST "cd /opt/hellotax/apm && docker-compose pull && docker-compose up -d"
  only:
    refs:
      - main
  when: manual
