stages:
  - build
  - deploy

variables:
  NODE_ENV: production
  SSH_PORT: "22"

cache:
  key:
    files:
      - package-lock.json
  paths:
    - node_modules/

build_site:
  stage: build
  image: node:22-alpine
  before_script:
    - node --version
    - npm --version
    - node -e "const [major, minor] = process.versions.node.split('.').map(Number); if (major < 22 || (major === 22 && minor < 12)) { console.error('Node 22.12.0 ou plus est requis.'); process.exit(1); }"
    - npm ci
  script:
    - npm run build
  artifacts:
    paths:
      - dist/
    expire_in: 1 week
  only:
    - branches
    - tags

deploy_vps:
  stage: deploy
  image: alpine:latest
  needs:
    - build_site
  before_script:
    - apk add --no-cache openssh-client rsync bash coreutils
    - 'command -v ssh >/dev/null || (echo "ssh est requis sur le runner" && exit 1)'
    - 'command -v rsync >/dev/null || (echo "rsync est requis sur le runner" && exit 1)'
    - eval "$(ssh-agent -s)"
    - |
      if [ -n "$OVH_SSH_PRIVATE_KEY_B64" ]; then
        printf '%s' "$OVH_SSH_PRIVATE_KEY_B64" | base64 -d | tr -d '\r' | ssh-add - > /dev/null
      elif [ -n "$SSH_PRIVATE_KEY" ]; then
        printf '%s' "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
      else
        echo "OVH_SSH_PRIVATE_KEY_B64 ou SSH_PRIVATE_KEY doit etre defini"
        exit 1
      fi
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan -p "$SSH_PORT" -H "$VPS_HOST" >> ~/.ssh/known_hosts
  script:
    - test -n "$VPS_USER" || (echo "VPS_USER n'est pas défini" && exit 1)
    - test -n "$VPS_HOST" || (echo "VPS_HOST n'est pas défini" && exit 1)
    - test -n "$VPS_PATH" || (echo "VPS_PATH n'est pas défini" && exit 1)
    - rsync -az --delete --exclude .git --exclude node_modules --exclude dist -e "ssh -p $SSH_PORT" ./ "$VPS_USER@$VPS_HOST:$VPS_PATH/"
    - |
      ssh -p "$SSH_PORT" "$VPS_USER@$VPS_HOST" "
        set -e
        mkdir -p '$VPS_PATH'
        cd '$VPS_PATH'
        IMAGE_TAG='${CI_COMMIT_SHORT_SHA:-latest}'
        IMAGE_NAME=iliacloud-site:
        docker build -t \"\${IMAGE_NAME}\${IMAGE_TAG}\" .
        docker tag \"\${IMAGE_NAME}\${IMAGE_TAG}\" iliacloud-site:latest
        ILIACLOUD_SITE_IMAGE=\"\${IMAGE_NAME}\${IMAGE_TAG}\" docker stack deploy -c docker-compose.yml iliacloud-site
        for i in \$(seq 1 30); do
          replicas=\$(docker service ls --filter name=iliacloud-site_site --format '{{.Replicas}}')
          if [ \"\$replicas\" = \"1/1\" ]; then
            exit 0
          fi
          sleep 2
        done
        echo \"Le service iliacloud-site_site n'a pas converge (replicas=\$replicas)\"
        docker service ps iliacloud-site_site --no-trunc || true
        exit 1
      "
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'