name: Release

on:
  push:
    tags: ['v*']
  workflow_dispatch:

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-22.04
            platform: linux
            arch: x64
          - os: macos-14
            platform: mac
            arch: arm64
          - os: windows-latest
            platform: win
            arch: x64

    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Read build configuration
        id: config
        shell: bash
        run: |
          NODE_VERSION=$(node -p "require('./.build-config.json').versions.node")
          PYTHON_VERSION=$(node -p "require('./.build-config.json').versions.python")
          DOTNET_VERSION=$(node -p "require('./.build-config.json').versions.dotnet")
          echo "node=$NODE_VERSION" >> $GITHUB_OUTPUT
          echo "python=$PYTHON_VERSION" >> $GITHUB_OUTPUT
          echo "dotnet=$DOTNET_VERSION" >> $GITHUB_OUTPUT
          echo "Node ${NODE_VERSION}, Python ${PYTHON_VERSION}, .NET ${DOTNET_VERSION}"

      - uses: actions/setup-node@v4
        with:
          node-version: ${{ steps.config.outputs.node }}

      - uses: actions/setup-python@v5
        with:
          python-version: ${{ steps.config.outputs.python }}

      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: ${{ steps.config.outputs.dotnet }}.x

      - name: Import Apple signing certificate
        if: matrix.platform == 'mac'
        env:
          APPLE_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_CERTIFICATE_P12_BASE64 }}
          APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
          KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
        run: |
          set -euo pipefail
          if [[ -z "${APPLE_CERTIFICATE_P12_BASE64:-}" ]]; then
              echo "APPLE_CERTIFICATE_P12_BASE64 not set — skipping (unsigned build)"
              exit 0
          fi
          printf '%s' "$APPLE_CERTIFICATE_P12_BASE64" | base64 --decode > "$RUNNER_TEMP/cert.p12"
          security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
          security default-keychain -s build.keychain
          security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
          security set-keychain-settings -lut 21600 build.keychain
          security list-keychains -d user -s build.keychain login.keychain-db
          security import "$RUNNER_TEMP/cert.p12" -k build.keychain \
              -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
          security set-key-partition-list \
              -S apple-tool:,apple:,codesign: \
              -s -k "$KEYCHAIN_PASSWORD" build.keychain
          rm -f "$RUNNER_TEMP/cert.p12"
          security find-identity -v -p codesigning build.keychain | grep -q "Developer ID Application"

      - name: Build
        run: ./scripts/build-release.sh
        shell: bash
        env:
          # PAT with read access to the private got-feedback repos so
          # build-common.sh can clone core + the bundled plugins.
          GH_CLONE_TOKEN: ${{ secrets.FEEDBACK_CLONE_TOKEN }}
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
          APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
          CSC_FOR_PULL_REQUEST: "true"

      - name: Setup upterm session
        uses: owenthereal/action-upterm@v1
        if: ${{ failure() }}
        with:
          wait-timeout-minutes: 5

      - name: Zip macOS app for tester distribution (non-tag)
        if: matrix.platform == 'mac' && !startsWith(github.ref, 'refs/tags/v')
        shell: bash
        run: |
          set -euo pipefail
          app=$(ls -d release/mac*/Slopsmith.app 2>/dev/null | head -n1 || true)
          if [[ -z "${app:-}" || ! -d "$app" ]]; then
            echo "::error::No Slopsmith.app found under release/mac*/ — macOS build produced no bundle."
            exit 1
          fi
          ditto -c -k --sequesterRsrc --keepParent "$app" "release/Slopsmith-macos-arm64.zip"
          echo "Zipped $app -> release/Slopsmith-macos-arm64.zip"
          ls -lh release/Slopsmith-macos-arm64.zip

      - name: Derive Velopack channel
        id: velopack_channel
        if: >-
          (startsWith(github.ref, 'refs/tags/v') && matrix.platform != 'linux')
          || (github.event_name == 'workflow_dispatch' && matrix.platform == 'win')
        shell: bash
        run: |
          set -euo pipefail
          if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
            base="$(node -p "require('./package.json').version")"
            base="${base%%-*}"
            channel=dev
            version="${base}-dev.${GITHUB_RUN_NUMBER}"
            echo "channel=$channel" >> "$GITHUB_OUTPUT"
            echo "version=$version" >> "$GITHUB_OUTPUT"
            echo "Manual dispatch -> channel=$channel version=$version"
            exit 0
          fi
          tag="${GITHUB_REF_NAME}"
          if [[ "$tag" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)-alpha\.[0-9]+$ ]]; then
            channel=alpha
            version="${BASH_REMATCH[1]}-alpha.${tag##*-alpha.}"
          elif [[ "$tag" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)-beta\.[0-9]+$ ]]; then
            channel=beta
            version="${BASH_REMATCH[1]}-beta.${tag##*-beta.}"
          elif [[ "$tag" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)-rc\.[0-9]+$ ]]; then
            channel=rc
            version="${BASH_REMATCH[1]}-rc.${tag##*-rc.}"
          elif [[ "$tag" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
            channel=stable
            version="${BASH_REMATCH[1]}"
          else
            echo "::error::Tag '$tag' does not match a known Velopack channel pattern (vX.Y.Z[-{alpha,beta,rc}.N]). Refusing to default to stable."
            exit 1
          fi
          echo "channel=$channel" >> "$GITHUB_OUTPUT"
          echo "version=$version" >> "$GITHUB_OUTPUT"
          echo "Derived channel=$channel version=$version from tag $tag"

      - name: Install Velopack CLI (vpk)
        if: steps.velopack_channel.outputs.channel != ''
        shell: bash
        run: |
          set -euo pipefail
          dotnet tool install -g vpk --version 0.0.1589-ga2c5a97
          echo "$HOME/.dotnet/tools" >> "$GITHUB_PATH"

      - name: Velopack pack (Windows)
        if: matrix.platform == 'win' && steps.velopack_channel.outputs.channel != ''
        shell: bash
        run: |
          set -euo pipefail
          vpk pack \
            --packId Slopsmith \
            --packVersion "${{ steps.velopack_channel.outputs.version }}" \
            --channel "win-x64-${{ steps.velopack_channel.outputs.channel }}" \
            --packDir release/win-unpacked \
            --msi \
            --instLocation PerMachine \
            -o release/velopack
          shopt -s nullglob nocaseglob
          removed=0
          for f in release/velopack/*setup.exe; do
            echo "Removing per-user installer: $f"
            rm -f "$f"
            removed=$((removed+1))
          done
          if compgen -G "release/velopack/*setup.exe" > /dev/null; then
            echo "::error::Setup.exe artifact(s) remain after cleanup; refusing to publish dual installer types."
            ls -1 release/velopack/*setup.exe
            exit 1
          fi
          if [[ "$removed" -eq 0 ]]; then
            echo "::notice::No Setup.exe output from vpk; shipping MSI-only artifacts."
          fi
          if ! compgen -G "release/velopack/*.msi" > /dev/null; then
            echo "::error::vpk pack --msi x64 did not produce a .msi file in release/velopack/"
            exit 1
          fi

      - name: Velopack pack (macOS)
        if: matrix.platform == 'mac' && steps.velopack_channel.outputs.channel != ''
        shell: bash
        env:
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
          APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
        run: |
          set -euo pipefail
          if [[ -z "${APPLE_SIGNING_IDENTITY:-}" || -z "${APPLE_ID:-}" \
                || -z "${APPLE_APP_SPECIFIC_PASSWORD:-}" \
                || -z "${APPLE_TEAM_ID:-}" ]]; then
            echo "::warning::Apple signing/notarization secrets incomplete — packing macOS Velopack release UNSIGNED. Gatekeeper will block auto-updates on user machines."
            vpk pack \
              --packId Slopsmith \
              --packVersion "${{ steps.velopack_channel.outputs.version }}" \
              --channel "osx-arm64-${{ steps.velopack_channel.outputs.channel }}" \
              --packDir release/mac-arm64/Slopsmith.app \
              -o release/velopack
          else
            xcrun notarytool store-credentials "velopack-notary" \
              --apple-id "$APPLE_ID" \
              --password "$APPLE_APP_SPECIFIC_PASSWORD" \
              --team-id "$APPLE_TEAM_ID"
            vpk pack \
              --packId Slopsmith \
              --packVersion "${{ steps.velopack_channel.outputs.version }}" \
              --channel "osx-arm64-${{ steps.velopack_channel.outputs.channel }}" \
              --packDir release/mac-arm64/Slopsmith.app \
              -o release/velopack \
              --signAppIdentity "$APPLE_SIGNING_IDENTITY" \
              --notaryProfile "velopack-notary"
          fi

      - name: Clean up signing keychain
        if: always() && matrix.platform == 'mac'
        run: |
          security delete-keychain build.keychain 2>/dev/null || true

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: slopsmith-${{ matrix.platform }}-${{ matrix.arch }}
          path: |
            release/*.AppImage
            release/*.deb
            release/*.exe
            release/velopack/**/*
            build/Release/*.pdb
            release/*.zip
          if-no-files-found: warn
          retention-days: 7

  release:
    needs: build
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            artifacts/**/*.AppImage
            artifacts/**/*.deb
            artifacts/**/velopack/**/*
          generate_release_notes: true
          prerelease: false
          make_latest: ${{ (contains(github.ref_name, '-alpha.') || contains(github.ref_name, '-beta.') || contains(github.ref_name, '-rc.')) && 'false' || 'true' }}

  notify-slopsmith:
    needs: release
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions: {}

    steps:
      - name: Dispatch VERSION sync to slopsmith
        env:
          GH_TOKEN: ${{ secrets.FEEDBACK_CLONE_TOKEN }}
          REF_NAME: ${{ github.ref_name }}
        run: |
          version="${REF_NAME#v}"
          if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Tag $REF_NAME is not vX.Y.Z — skipping slopsmith VERSION sync."
            exit 0
          fi
          if [ -z "${GH_TOKEN:-}" ]; then
            echo "::error::FEEDBACK_CLONE_TOKEN secret is missing; cannot dispatch."
            exit 1
          fi
          gh api -X POST repos/got-feedback/feedback/dispatches \
            -f event_type=desktop-released \
            -f "client_payload[version]=$version"
          echo "Dispatched desktop-released event (version=$version) to slopsmith."
