name: Build Release

on:
  push:
    branches:
      - main
      - master
    tags:
      - "*"
  workflow_dispatch:

permissions:
  actions: read
  contents: read

jobs:
  android:
    name: Build Android
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          repository: gongyun/app
          ref: ${{ github.ref }}
          token: ${{ secrets.GITEA_TOKEN }}
          github-server-url: https://git.saont.net

      - name: Set up Java
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "17"

      - name: Set up Flutter
        uses: subosito/flutter-action@v2
        with:
          channel: stable
          cache: true

      - name: Install dependencies
        run: flutter pub get

      - name: Restore Android signing files
        shell: bash
        env:
          ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
          ANDROID_STORE_PASSWORD: ${{ secrets.ANDROID_STORE_PASSWORD }}
          ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
          ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
        run: |
          if [ -z "$ANDROID_KEYSTORE_BASE64" ] || [ -z "$ANDROID_STORE_PASSWORD" ] || [ -z "$ANDROID_KEY_ALIAS" ] || [ -z "$ANDROID_KEY_PASSWORD" ]; then
            echo "Android signing secrets are required: ANDROID_KEYSTORE_BASE64, ANDROID_STORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD"
            exit 1
          fi

          printf "%s" "$ANDROID_KEYSTORE_BASE64" | base64 -d > android/app-release.jks
          cat > android/key.properties <<EOF
          storeFile=../app-release.jks
          storePassword=$ANDROID_STORE_PASSWORD
          keyAlias=$ANDROID_KEY_ALIAS
          keyPassword=$ANDROID_KEY_PASSWORD
          EOF

      - name: Build Android release APK
        run: flutter build apk --release

      - name: Rename Android APK
        run: cp build/app/outputs/flutter-apk/app-release.apk gongyun-app-release.apk

      - name: Upload Android APK artifact
        uses: actions/upload-artifact@v4
        with:
          name: android-release
          path: gongyun-app-release.apk

  # windows:
  #   name: Build Windows
  #   runs-on: windows-latest
  #
  #   steps:
  #     - name: Checkout
  #       uses: actions/checkout@v4
  #       with:
  #         repository: gongyun/app
  #         ref: ${{ github.ref }}
  #         token: ${{ secrets.GITEA_TOKEN }}
  #         github-server-url: https://git.saont.net
  #
  #     - name: Set up Flutter
  #       uses: subosito/flutter-action@v2
  #       with:
  #         channel: stable
  #         cache: true
  #
  #     - name: Enable Windows desktop
  #       run: flutter config --enable-windows-desktop
  #
  #     - name: Install dependencies
  #       run: flutter pub get
  #
  #     - name: Build Windows release
  #       run: flutter build windows --release
  #
  #     - name: Package Windows release
  #       shell: pwsh
  #       run: Compress-Archive -Path build\windows\x64\runner\Release\* -DestinationPath gongyun.zip -Force
  #
  #     - name: Upload Windows artifact
  #       uses: actions/upload-artifact@v4
  #       with:
  #         name: windows-release
  #         path: gongyun.zip

  release:
    name: Publish Release
    runs-on: ubuntu-latest
    needs:
      - android
      # - windows
    if: startsWith(github.ref, 'refs/tags/')
    permissions:
      actions: read
      contents: read
      releases: write

    steps:
      - name: Download Android artifact
        uses: actions/download-artifact@v4
        with:
          name: android-release
          path: dist

      # - name: Download Windows artifact
      #   uses: actions/download-artifact@v4
      #   with:
      #     name: windows-release
      #     path: dist

      - name: Publish Gitea release
        shell: bash
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
          GITEA_API_URL: https://git.saont.net/api/v1
          GITEA_OWNER: gongyun
          GITEA_REPO: app
          TAG_NAME: ${{ github.ref_name }}
          TARGET_COMMITISH: ${{ github.sha }}
        run: |
          set -euo pipefail

          if [ -z "${GITEA_TOKEN:-}" ]; then
            echo "GITEA_TOKEN is required to publish release assets."
            exit 1
          fi

          RELEASES_URL="$GITEA_API_URL/repos/$GITEA_OWNER/$GITEA_REPO/releases"
          RELEASE_BY_TAG_URL="$RELEASES_URL/tags/$TAG_NAME"

          status=$(curl -sS -o release.json -w "%{http_code}" \
            -H "Authorization: token $GITEA_TOKEN" \
            "$RELEASE_BY_TAG_URL")

          if [ "$status" = "404" ]; then
            release_payload=$(python3 - <<'PY'
          import json
          import os

          tag = os.environ["TAG_NAME"]
          print(json.dumps({
              "tag_name": tag,
              "target_commitish": os.environ.get("TARGET_COMMITISH", ""),
              "name": tag,
              "body": f"Automated release for {tag}.",
              "draft": False,
              "prerelease": False,
          }))
          PY
          )

            status=$(curl -sS -o release.json -w "%{http_code}" \
              -X POST \
              -H "Authorization: token $GITEA_TOKEN" \
              -H "Content-Type: application/json" \
              -d "$release_payload" \
              "$RELEASES_URL")
          fi

          if [ "$status" != "200" ] && [ "$status" != "201" ]; then
            echo "Failed to create or load release. HTTP status: $status"
            cat release.json
            exit 1
          fi

          RELEASE_ID=$(python3 - <<'PY'
          import json

          with open("release.json", encoding="utf-8") as f:
              print(json.load(f)["id"])
          PY
          )

          ASSETS_URL="$RELEASES_URL/$RELEASE_ID/assets"

          curl -sS -f \
            -H "Authorization: token $GITEA_TOKEN" \
            "$ASSETS_URL" \
            -o assets.json

          python3 - <<'PY' > asset-ids-to-delete.txt
          import json

          names = {"gongyun-app-release.apk"}
          with open("assets.json", encoding="utf-8") as f:
              for asset in json.load(f):
                  if asset.get("name") in names:
                      print(asset["id"])
          PY

          while IFS= read -r asset_id; do
            if [ -n "$asset_id" ]; then
              curl -sS -f \
                -X DELETE \
                -H "Authorization: token $GITEA_TOKEN" \
                "$ASSETS_URL/$asset_id"
            fi
          done < asset-ids-to-delete.txt

          upload_asset() {
            local file="$1"
            local name
            name="$(basename "$file")"

            curl -sS -f \
              -X POST \
              -H "Authorization: token $GITEA_TOKEN" \
              -F "attachment=@$file" \
              "$ASSETS_URL?name=$name"
          }

          upload_asset dist/gongyun-app-release.apk
          # upload_asset dist/gongyun.zip
