name: Daily Neon Database Backup

on:
  schedule:
    - cron: "0 2 * * *"

  workflow_dispatch:

jobs:
  backup:
    runs-on: ubuntu-latest

    steps:
      - name: Install PostgreSQL 17 client
        run: |
          sudo apt-get update
          sudo apt-get install -y curl ca-certificates gnupg
          curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo gpg --dearmor -o /usr/share/keyrings/postgresql.gpg
          echo "deb [signed-by=/usr/share/keyrings/postgresql.gpg] http://apt.postgresql.org/pub/repos/apt noble-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list
          sudo apt-get update
          sudo apt-get install -y postgresql-client-17
          pg_dump --version

      - name: Create backup
        env:
          DATABASE_URL: ${{ secrets.DATABASE_URL }}
        run: |
          mkdir -p backups
          DATE=$(date +"%Y-%m-%d_%H-%M-%S")
          /usr/lib/postgresql/17/bin/pg_dump "$DATABASE_URL" \
            --format=custom \
            --no-owner \
            --no-privileges \
            --file="backups/neon-backup-$DATE.dump"

      - name: Upload backup artifact
        uses: actions/upload-artifact@v4
        with:
          name: neon-database-backup
          path: backups/*.dump
          retention-days: 30
