name: Deploy Media Server
on:
  push:
    branches: [ "master" ]
  workflow_dispatch: {}
permissions:
  contents: read
concurrency:
  group: deploy-media-${{ github.ref }}
  cancel-in-progress: true
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - 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: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: media-publish
          path: ./publish
  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment: production
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v4
        with:
          name: media-publish
          path: publish
      - name: Prepare SSH
        run: |
          install -m 700 -d ~/.ssh
          echo "${{ secrets.MEDIA_SSH_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -p "${{ secrets.SSH_PORT || 22 }}" "${{ secrets.SSH_HOST }}" >> ~/.ssh/known_hosts || true
      - name: Rsync to nginx server
        run: |
          echo "Connecting to: ${{ secrets.MEDIA_DEPLOY_USER }}@${{ secrets.SSH_HOST }}:${{ secrets.SSH_PORT || 22 }}"
          echo "Testing SSH connection first..."
          ssh -v -i ~/.ssh/deploy_key -p "${{ secrets.SSH_PORT || 22 }}" \
            -o StrictHostKeyChecking=no \
            ${{ secrets.MEDIA_DEPLOY_USER }}@${{ secrets.SSH_HOST }} "echo 'SSH connection successful'"
          echo "Running rsync..."
          rsync -az --delete -e "ssh -p ${{ secrets.SSH_PORT || 22 }} -i ~/.ssh/deploy_key -o StrictHostKeyChecking=no" \
            publish/ ${{ secrets.MEDIA_DEPLOY_USER }}@${{ secrets.SSH_HOST }}:/tmp/media-app-deploy/
      - name: Copy to media server and restart
        run: |
          ssh -i ~/.ssh/deploy_key -p "${{ secrets.SSH_PORT || 22 }}" \
            ${{ secrets.MEDIA_DEPLOY_USER }}@${{ secrets.SSH_HOST }} \
            "ssh josh@10.0.0.180 'mkdir -p /tmp/media-app-temp' && \
             scp -r /tmp/media-app-deploy/* josh@10.0.0.180:/tmp/media-app-temp/ && \
             ssh josh@10.0.0.180 'sudo rsync -av --delete --exclude=App_Data /tmp/media-app-temp/ /var/www/media-app/ && \
                                  sudo mkdir -p /var/www/media-app/App_Data/media && \
                                  sudo chown -R www-data:www-data /var/www/media-app/App_Data && \
                                  sudo systemctl daemon-reload && \
                                  sudo systemctl restart media-app && \
                                  rm -rf /tmp/media-app-temp' && \
             rm -rf /tmp/media-app-deploy"