name: Deploy to VPS

on:
  push:
    branches:
      - master
  workflow_dispatch:

permissions:
  contents: read
  packages: write

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Log in to GHCR
        run: echo "${{ github.token }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin

      - name: Build and push Docker image
        env:
          IMAGE_NAME: ghcr.io/mytheclipse/bete:${{ github.sha }}
        run: |
          docker build -t "$IMAGE_NAME" .
          docker push "$IMAGE_NAME"

      - name: Deploy to VPS
        env:
          VPS_HOST: ${{ secrets.VPS_HOST }}
          VPS_USERNAME: ${{ secrets.VPS_USERNAME }}
          VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
          ENV_FILE: ${{ secrets.ENV_FILE }}
          GITHUB_TOKEN: ${{ github.token }}
          GITHUB_ACTOR: ${{ github.actor }}
          IMAGE_NAME: ghcr.io/mytheclipse/bete:${{ github.sha }}
        run: |
          # 1. Setup SSH Key
          mkdir -p ~/.ssh
          echo "$VPS_SSH_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "$VPS_HOST" >> ~/.ssh/known_hosts
          
          # 2. Pull image and start containers on VPS
          ssh -i ~/.ssh/id_ed25519 -o StrictHostKeyChecking=no "$VPS_USERNAME@$VPS_HOST" "
            set -e
            APP_DIR=/opt/imphenbot
            mkdir -p \$APP_DIR
            cd \$APP_DIR

            echo \"$GITHUB_TOKEN\" | docker login ghcr.io -u \"$GITHUB_ACTOR\" --password-stdin

            printf '%s\nIMAGE_NAME=$IMAGE_NAME' \"$ENV_FILE\" > .env

            if command -v docker-compose &> /dev/null; then
              docker-compose down || true
              docker-compose pull
              docker-compose up -d
            else
              docker compose down || true
              docker compose pull
              docker compose up -d
            fi
          "
