name: Auto Update Vesktop Template

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

jobs:
  update-template:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Install Dependencies
        run: sudo apt-get update && sudo apt-get install -y curl jq

      - name: Fetch Latest Stable Release
        id: get_release
        run: |
          RELEASES=$(curl -s -H "User-Agent: gitea-actions" https://api.github.com/repos/Vencord/Vesktop/releases?per_page=50)
          VERSION=$(echo "$RELEASES" | jq -r '[.[] | select(.tag_name | test("^v?\\d+\\.\\d+\\.\\d+$"))] | sort_by(.published_at) | reverse | .[0].tag_name' || echo "")
          if [[ -z "$VERSION" ]]; then
            echo "No stable release found"
            exit 0
          fi
          DEB_URL=$(echo "$RELEASES" | jq -r "[.[] | select(.tag_name == \"$VERSION\")] | .[0].assets[] | select(.name | test(\"vesktop_.*_amd64\\\\.deb$\")) | .browser_download_url" || echo "")
          if [[ -z "$DEB_URL" ]]; then
            echo "No .deb found"
            exit 0
          fi
          VERSION=${VERSION#v} # Remove 'v' prefix if present
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "deb_url=$DEB_URL" >> $GITHUB_OUTPUT

      - name: Read Current Version
        if: steps.get_release.outputs.version
        id: check_version
        run: |
          CURRENT_VERSION=$(grep '^version=' template | cut -d= -f2)
          echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT

      - name: Download and Checksum
        if: steps.get_release.outputs.version && steps.get_release.outputs.version != steps.check_version.outputs.current_version
        id: download
        run: |
          curl -Lo vesktop.deb "${{ steps.get_release.outputs.deb_url }}"
          SHA256=$(sha256sum vesktop.deb | awk '{print $1}')
          echo "sha256=$SHA256" >> $GITHUB_OUTPUT

      - name: Update Template
        if: steps.get_release.outputs.version && steps.get_release.outputs.version != steps.check_version.outputs.current_version
        run: |
          sed -i "s/^version=.*/version=${{ steps.get_release.outputs.version }}/" template
          sed -i "s/^checksum=.*/checksum=${{ steps.download.outputs.sha256 }}/" template

      - name: Commit and Push
        if: steps.get_release.outputs.version && steps.get_release.outputs.version != steps.check_version.outputs.current_version
        run: |
         git config user.name "Wizzard"
          git config user.email "rich@bandaholics.cash"
          git add template
          git commit -m "Update to v${{ steps.get_release.outputs.version }} [auto]"
          git push