name: 🪞 Mirror to Codeberg
on:
  push:
    branches: [main]
  workflow_dispatch:
  schedule:
    - cron: "30 0 * * 0"

jobs:
  codeberg:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Configure SSH
        run: |
          mkdir -p ~/.ssh
          printf '%s\n' "${{ secrets.CODEBERG_SSH }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H codeberg.org >> ~/.ssh/known_hosts
          cat <<'EOF' > ~/.ssh/config
          Host codeberg.org
            HostName codeberg.org
            User git
            IdentityFile ~/.ssh/id_ed25519
            IdentitiesOnly yes
          EOF

      - name: Verify SSH access
        run: |
          ssh -T git@codeberg.org || true
          git ls-remote git@codeberg.org:adrian-altner/adrian-altner.com.git > /dev/null

      - name: Mirror to Codeberg
        run: |
          git remote add mirror git@codeberg.org:adrian-altner/adrian-altner.com.git
          # Remove previously mirrored remote-tracking refs (e.g. refs/remotes/origin/*).
          while IFS= read -r ref; do
            git push mirror ":${ref}"
          done < <(git ls-remote --refs mirror 'refs/remotes/*' | awk '{print $2}')

          # Mirror only real branches and tags.
          git push --prune mirror \
            +refs/heads/*:refs/heads/* \
            +refs/tags/*:refs/tags/*