# .gitea/workflows/deploy.yml
name: Deploy Media Server

on:
  push:
    branches: [ "master" ]
  workflow_dispatch: {}

concurrency:
  group: deploy-media-${{ gitea.ref }}
  cancel-in-progress: true

jobs:
  build-deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Install toolchain
        run: |
          apt-get update
          apt-get install -y --no-install-recommends rsync openssh-client

      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '8.0.x'

      - name: Restore
        run: dotnet restore

      - name: Publish
        run: dotnet publish -c Release -o ./publish

      - name: Prepare SSH
        env:
          SSH_KEY:  ${{ secrets.MEDIA_SSH_KEY }}
          SSH_HOST: ${{ secrets.MEDIA_SSH_HOST }}
          SSH_PORT: ${{ secrets.MEDIA_SSH_PORT }}
        run: |
          set -euo pipefail
          PORT="${SSH_PORT:-22}"
          install -m 700 -d ~/.ssh
          printf '%s\n' "$SSH_KEY" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -p "$PORT" "$SSH_HOST" >> ~/.ssh/known_hosts 2>/dev/null

      # Staged through /tmp because the deploy user can't write /var/www directly.
      # /usr/local/sbin/deploy-media (root-owned, the only command in deploy's
      # sudoers) moves it into place with --exclude=App_Data, so the uploaded
      # media and its encrypted store are never touched by --delete.
      - name: Stage publish output
        env:
          SSH_HOST: ${{ secrets.MEDIA_SSH_HOST }}
          SSH_PORT: ${{ secrets.MEDIA_SSH_PORT }}
          SSH_USER: ${{ secrets.MEDIA_SSH_USER }}
        run: |
          set -euo pipefail
          PORT="${SSH_PORT:-22}"
          SSH_OPTS="-p $PORT -i $HOME/.ssh/deploy_key -o StrictHostKeyChecking=yes"
          ssh $SSH_OPTS "$SSH_USER@$SSH_HOST" \
            "rm -rf /tmp/media-app-stage && mkdir -p /tmp/media-app-stage"
          rsync -az --delete -e "ssh $SSH_OPTS" \
            publish/ "$SSH_USER@$SSH_HOST:/tmp/media-app-stage/"

      - name: Install and restart
        env:
          SSH_HOST: ${{ secrets.MEDIA_SSH_HOST }}
          SSH_PORT: ${{ secrets.MEDIA_SSH_PORT }}
          SSH_USER: ${{ secrets.MEDIA_SSH_USER }}
        run: |
          set -euo pipefail
          PORT="${SSH_PORT:-22}"
          ssh -p "$PORT" -i "$HOME/.ssh/deploy_key" "$SSH_USER@$SSH_HOST" \
            "sudo -n /usr/local/sbin/deploy-media && rm -rf /tmp/media-app-stage"