stages:
  - publish
  - deploy

variables:
  REGISTRY: registry.gitlab.com/$CI_PROJECT_PATH

.deploy_template: &deploy_setup
  stage: deploy
  image: alpine:3.20
  before_script:
    - apk add --no-cache openssh-client
    - mkdir -p ~/.ssh
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_ed25519
    - chmod 600 ~/.ssh/id_ed25519
    - ssh-keyscan -H $VPS_HOST >> ~/.ssh/known_hosts
  environment:
    name: production
    url: https://balexvic.com

publish:
  stage: publish
  image: docker:27
  services:
    - docker:27-dind
  variables:
    DOCKER_TLS_CERTDIR: ""
  before_script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin
  script:
    - docker build -t $REGISTRY:${CI_COMMIT_SHORT_SHA} -t $REGISTRY:latest .
    - docker push $REGISTRY:${CI_COMMIT_SHORT_SHA}
    - docker push $REGISTRY:latest
  rules:
    - if: $CI_COMMIT_BRANCH == "main"

deploy:
  <<: *deploy_setup
  needs: [publish]
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  script:
    - |
      ssh $VPS_USER@$VPS_HOST << ENDSSH
        set -e
        echo "$CI_REGISTRY_PASSWORD" | docker login registry.gitlab.com -u "$CI_REGISTRY_USER" --password-stdin
        cd /opt/services
        docker compose -f docker-compose.yml -f docker-compose.prod.yml pull audio-foreign
        docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d audio-foreign
        docker image prune -af
      ENDSSH
