name: 🏥 Server Maintenance

on:
  schedule:
    - cron: '0 3 * * *' # Every day at 3:00 AM
  workflow_dispatch: # Allow manual trigger

jobs:
  maintenance:
    name: 🧹 Prune & Clean
    runs-on: docker
    container:
      image: catthehacker/ubuntu:act-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: 🚀 Execute Maintenance via SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.SSH_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H ${{ secrets.SSH_HOST }} >> ~/.ssh/known_hosts 2>/dev/null

          # Run the prune script on the host
          # We transfer the script and execute it to ensure it matches the repo version
          scp packages/infra/scripts/prune-registry.sh root@${{ secrets.SSH_HOST }}:/tmp/prune-registry.sh
          ssh root@${{ secrets.SSH_HOST }} "bash /tmp/prune-registry.sh && rm /tmp/prune-registry.sh"

      - name: 🔔 Notification - Success
        if: success()
        run: |
          curl -s -k -X POST "${{ secrets.GOTIFY_URL }}/message?token=${{ secrets.GOTIFY_TOKEN }}" \
            -F "title=🏥 Maintenance Complete" \
            -F "message=Server-Wartung erfolgreich ausgeführt.\nRegistry & Docker Ressourcen bereinigt." \
            -F "priority=2" || true

      - name: 🔔 Notification - Failure
        if: failure()
        run: |
          curl -s -k -X POST "${{ secrets.GOTIFY_URL }}/message?token=${{ secrets.GOTIFY_TOKEN }}" \
            -F "title=❌ Maintenance FAILED" \
            -F "message=Die automatische Server-Wartung ist fehlgeschlagen!\nBitte Logs prüfen." \
            -F "priority=8" || true
