name: Update-Athena-LED

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

env:
  GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}

permissions: write-all

jobs:
  cleanup:
    runs-on: ubuntu-22.04
    steps:
      - name: Delete old Releases and Workflows
        uses: ophub/delete-releases-workflows@main
        with:
          gh_token: ${{secrets.GITHUB_TOKEN}}
          delete_workflows: true
          workflows_keep_day: 0

  update:
    runs-on: ubuntu-22.04
    needs: cleanup
    steps:
      - name: Checkout Projects
        uses: actions/checkout@main

      - name: Update Athena LED
        run: |
          cd ./package/emortal/
          PKG_NAME=luci-app-athena-led

          LOCAL_HASH=$(cat "./$PKG_NAME/.latest_commit" 2>/dev/null || echo "none")
          REMOTE_HASH=$(curl -sL https://api.github.com/repos/NONGFAH/luci-app-athena-led/commits/main | jq -r '.sha' | cut -c1-8)

          if [[ "$LOCAL_HASH" != "$REMOTE_HASH" ]]; then
            rm -rf ./$PKG_NAME
            curl -sL -o ./athena-led.zip https://github.com/NONGFAH/luci-app-athena-led/archive/refs/heads/main.zip
            unzip ./athena-led.zip -d ./
            mv ./luci-app-athena-led-main ./$PKG_NAME && rm -rf ./athena-led.zip
            chmod +x -R ./$PKG_NAME/root/usr/sbin/* && chmod +x -R ./$PKG_NAME/root/etc/init.d/*

            echo "$PKG_NAME has been updated to $REMOTE_HASH!"

            echo "$REMOTE_HASH" > "./$PKG_NAME/.latest_commit"
            echo "PKG_NAME=$PKG_NAME" >> "$GITHUB_ENV"
            echo "REMOTE_HASH=$REMOTE_HASH" >> "$GITHUB_ENV"
          else
            echo "$PKG_NAME is already the latest!"
          fi

          [ -z "$(git status -s)" ] || echo -e "CHANGE_STAT=1" >> "$GITHUB_ENV"

      - name: Commit Changes
        if: ${{ env.CHANGE_STAT }}
        run: |
          git config --local user.name "github-actions[bot]"
          git config --local user.email "<github-actions[bot]@users.noreply.github.com>"
          git add .
          git commit -m "${{env.PKG_NAME}}: update version to ${{env.REMOTE_HASH}}"
          git push -f origin HEAD:main
