name: Update Flake Lock

on:
  schedule:
    - cron: '0 4 * * *'
  workflow_dispatch:

jobs:
  update:
    runs-on: x86_64
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Update flake.lock
        id: update
        run: |
          source /etc/bashrc
          
          nix flake update
          
          if git diff --quiet flake.lock; then
            echo "No changes to flake.lock"
            echo "updated=false" >> $GITHUB_OUTPUT
          else
            echo "flake.lock updated"
            echo "updated=true" >> $GITHUB_OUTPUT
          fi

      - name: Create Pull Request
        if: steps.update.outputs.updated == 'true'
        env:
          API_FORGEJO_TOKEN: ${{ secrets.API_FORGEJO_TOKEN }}
        run: |
          source /etc/bashrc
          
          DATE=$(date +%Y-%m-%d)
          BRANCH="update/flake-lock-${DATE}"
          
          git config user.name "mizuki"
          git config user.email "akiyama@mizuki.guru"
          
          git checkout -b "$BRANCH"
          git add flake.lock
          git commit -m "flake.lock: update ${DATE}"
          
          REPO_URL=$(git remote get-url origin | sed 's|https://||')
          git push -f "https://oauth2:${API_FORGEJO_TOKEN}@${REPO_URL}" "$BRANCH"
          
          FORGEJO_HOST=$(echo "$REPO_URL" | cut -d'/' -f1)
          REPO_PATH=$(echo "$REPO_URL" | cut -d'/' -f2-)
          
          curl -fsSL -X POST \
            -H "Authorization: token ${API_FORGEJO_TOKEN}" \
            -H "Content-Type: application/json" \
            "https://${FORGEJO_HOST}/api/v1/repos/${REPO_PATH}/pulls" \
            -d "{
              \"title\": \"flake.lock: update ${DATE}\",
              \"head\": \"${BRANCH}\",
              \"base\": \"main\",
              \"body\": \"Automated flake.lock update generated by Forgejo Actions.\"
            }"
