# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
# SPDX-License-Identifier: GPL-3.0-or-later
# FILE INFORMATION
# DEFGROUP: Gitea.Workflow
# INGROUP: MokoCassiopeia.Automation
# REPO: https://git.mokoconsulting.tech/MokoConsulting/MokoCassiopeia
# PATH: /.github/workflows/auto-update-sha.yml
# VERSION: 03.09.03
# BRIEF: Automatically update SHA-256 hash in updates.xml after release
# NOTE: Ensures updates.xml stays synchronized with release packages

name: Auto-Update SHA Hash

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      tag:
        description: 'Release tag to update SHA for (e.g., 03.08.03)'
        required: true
        type: string

permissions:
  contents: write

jobs:
  update-sha:
    name: Update SHA-256 Hash in updates.xml
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: main

      - name: Get release tag
        id: tag
        run: |
          if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
            TAG="${{ inputs.tag }}"
          else
            TAG="${{ github.event.release.tag_name }}"
          fi
          echo "tag=${TAG}" >> $GITHUB_OUTPUT
          echo "Processing release: ${TAG}"

      - name: Download release package
        run: |
          TAG="${{ steps.tag.outputs.tag }}"
          PACKAGE_NAME="mokocassiopeia-src-${TAG}.zip"
          DOWNLOAD_URL="https://github.com/${{ github.repository }}/releases/download/${TAG}/${PACKAGE_NAME}"
          
          echo "Downloading: ${DOWNLOAD_URL}"
          curl -L -o "${PACKAGE_NAME}" "${DOWNLOAD_URL}"
          
          if [ ! -f "${PACKAGE_NAME}" ]; then
            echo "Error: Failed to download package"
            exit 1
          fi
          
          echo "PACKAGE_NAME=${PACKAGE_NAME}" >> $GITHUB_ENV

      - name: Calculate SHA-256 hash
        id: sha
        run: |
          SHA256_HASH=$(sha256sum "${PACKAGE_NAME}" | cut -d' ' -f1)
          echo "sha256=${SHA256_HASH}" >> $GITHUB_OUTPUT
          echo "SHA-256 Hash: ${SHA256_HASH}"

      - name: Determine stability channel
        id: channel
        run: |
          TAG="${{ steps.tag.outputs.tag }}"
          case "$TAG" in
            development) STABILITY="development" ;;
            alpha)       STABILITY="alpha" ;;
            beta)        STABILITY="beta" ;;
            release-candidate) STABILITY="rc" ;;
            *)           STABILITY="stable" ;;
          esac
          echo "stability=${STABILITY}" >> $GITHUB_OUTPUT
          echo "Channel: ${STABILITY}"

      - name: Update updates.xml (targeted channel only)
        env:
          PY_TAG: ${{ steps.tag.outputs.tag }}
          PY_SHA: ${{ steps.sha.outputs.sha256 }}
          PY_STABILITY: ${{ steps.channel.outputs.stability }}
        run: |
          DATE=$(date +%Y-%m-%d)
          export PY_DATE="$DATE"

          python3 << 'PYEOF'
          import re, os

          tag       = os.environ["PY_TAG"]
          sha256    = os.environ["PY_SHA"]
          date      = os.environ["PY_DATE"]
          stability = os.environ["PY_STABILITY"]

          with open("updates.xml") as f:
              content = f.read()

          pattern = r"(<update>(?:(?!</update>).)*?<tag>" + re.escape(stability) + r"</tag>.*?</update>)"
          match = re.search(pattern, content, re.DOTALL)

          if not match:
              print(f"No <update> block for <tag>{stability}</tag> — skipping")
              exit(0)

          block = match.group(1)
          original = block

          block = re.sub(r"<sha256>[^<]*</sha256>", f"<sha256>{sha256}</sha256>", block)
          block = re.sub(r"<creationDate>[^<]*</creationDate>", f"<creationDate>{date}</creationDate>", block)

          content = content.replace(original, block)

          with open("updates.xml", "w") as f:
              f.write(content)

          print(f"Updated {stability} channel: sha={sha256[:16]}..., date={date}")
          PYEOF

      - name: Check for changes
        id: changes
        run: |
          if git diff --quiet updates.xml; then
            echo "has_changes=false" >> $GITHUB_OUTPUT
            echo "No changes to updates.xml"
          else
            echo "has_changes=true" >> $GITHUB_OUTPUT
            echo "Changes detected in updates.xml"
            git diff updates.xml
          fi

      - name: Commit and push changes
        if: steps.changes.outputs.has_changes == 'true'
        run: |
          TAG="${{ steps.tag.outputs.tag }}"
          
          git config --local user.email "gitea-actions[bot]@mokoconsulting.tech"
          git config --local user.name "gitea-actions[bot]"
          
          STABILITY="${{ steps.channel.outputs.stability }}"
          git add updates.xml
          git commit -m "chore: update ${STABILITY} SHA-256 for ${TAG} [skip ci]" \
            --author="gitea-actions[bot] <gitea-actions[bot]@mokoconsulting.tech>"
          
          git push origin main
          
          echo "Successfully updated updates.xml with SHA-256 hash for release ${TAG}"

      - name: Summary
        if: steps.changes.outputs.has_changes == 'true'
        run: |
          echo "### SHA-256 Hash Updated Successfully" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- Release: ${{ steps.tag.outputs.tag }}" >> $GITHUB_STEP_SUMMARY
          echo "- SHA-256: \`${{ steps.sha.outputs.sha256 }}\`" >> $GITHUB_STEP_SUMMARY
          echo "- File: updates.xml" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "The Joomla update server will now provide the correct package hash." >> $GITHUB_STEP_SUMMARY

      - name: Summary (no changes)
        if: steps.changes.outputs.has_changes == 'false'
        run: |
          echo "### No Updates Needed" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "updates.xml already contains the correct SHA-256 hash for release ${{ steps.tag.outputs.tag }}" >> $GITHUB_STEP_SUMMARY
