name: Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

jobs:
  create-release:
    permissions:
      contents: write
    runs-on: ubuntu-22.04
    outputs:
      release_id: ${{ steps.create-release.outputs.result }}

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Get version
        run: echo "PACKAGE_VERSION=$(node -p "require('./package.json').version")" >> $GITHUB_ENV

      - name: Create release
        id: create-release
        uses: actions/github-script@v7
        with:
          script: |
            const { data } = await github.rest.repos.createRelease({
              owner: context.repo.owner,
              repo: context.repo.repo,
              tag_name: `v${process.env.PACKAGE_VERSION}`,
              name: `haex-hub v${process.env.PACKAGE_VERSION}`,
              body: 'Take a look at the assets to download and install this app.',
              draft: true,
              prerelease: false
            })
            return data.id

  build-desktop:
    needs: create-release
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: 'macos-latest'
            args: '--target aarch64-apple-darwin'
          - platform: 'macos-latest'
            args: '--target x86_64-apple-darwin'
          - platform: 'ubuntu-22.04'
            args: ''
          - platform: 'windows-latest'
            args: ''

    runs-on: ${{ matrix.platform }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install pnpm
        uses: pnpm/action-setup@v4

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}

      - name: Install dependencies (Ubuntu)
        if: matrix.platform == 'ubuntu-22.04'
        run: |
          sudo apt-get update
          sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev

      - name: Get pnpm store directory
        shell: bash
        run: |
          echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV

      - name: Setup pnpm cache
        uses: actions/cache@v4
        with:
          path: ${{ env.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-

      - name: Setup Rust cache
        uses: Swatinem/rust-cache@v2
        with:
          workspaces: src-tauri

      - name: Install frontend dependencies
        run: pnpm install --frozen-lockfile

      - name: Build and release Tauri app
        uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          releaseId: ${{ needs.create-release.outputs.release_id }}
          args: ${{ matrix.args }}

  build-android:
    needs: create-release
    permissions:
      contents: write
    runs-on: ubuntu-22.04
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install pnpm
        uses: pnpm/action-setup@v4

      - name: Setup Java
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '17'

      - name: Setup Android SDK
        uses: android-actions/setup-android@v3

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Install Rust Android targets
        run: |
          rustup target add aarch64-linux-android
          rustup target add armv7-linux-androideabi
          rustup target add i686-linux-android
          rustup target add x86_64-linux-android

      - name: Setup NDK
        uses: nttld/setup-ndk@v1
        with:
          ndk-version: r26d
        id: setup-ndk

      - name: Setup Android NDK environment for OpenSSL
        run: |
          echo "ANDROID_NDK_HOME=${{ steps.setup-ndk.outputs.ndk-path }}" >> $GITHUB_ENV
          echo "NDK_HOME=${{ steps.setup-ndk.outputs.ndk-path }}" >> $GITHUB_ENV

          # Add all Android toolchains to PATH for OpenSSL cross-compilation
          echo "${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin" >> $GITHUB_PATH

          # Set CC, AR, RANLIB for each target
          echo "CC_aarch64_linux_android=aarch64-linux-android24-clang" >> $GITHUB_ENV
          echo "AR_aarch64_linux_android=llvm-ar" >> $GITHUB_ENV
          echo "RANLIB_aarch64_linux_android=llvm-ranlib" >> $GITHUB_ENV

          echo "CC_armv7_linux_androideabi=armv7a-linux-androideabi24-clang" >> $GITHUB_ENV
          echo "AR_armv7_linux_androideabi=llvm-ar" >> $GITHUB_ENV
          echo "RANLIB_armv7_linux_androideabi=llvm-ranlib" >> $GITHUB_ENV

          echo "CC_i686_linux_android=i686-linux-android24-clang" >> $GITHUB_ENV
          echo "AR_i686_linux_android=llvm-ar" >> $GITHUB_ENV
          echo "RANLIB_i686_linux_android=llvm-ranlib" >> $GITHUB_ENV

          echo "CC_x86_64_linux_android=x86_64-linux-android24-clang" >> $GITHUB_ENV
          echo "AR_x86_64_linux_android=llvm-ar" >> $GITHUB_ENV
          echo "RANLIB_x86_64_linux_android=llvm-ranlib" >> $GITHUB_ENV

      - name: Install build dependencies for OpenSSL
        run: |
          sudo apt-get update
          sudo apt-get install -y perl make

      - name: Get pnpm store directory
        shell: bash
        run: |
          echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV

      - name: Setup pnpm cache
        uses: actions/cache@v4
        with:
          path: ${{ env.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-

      - name: Setup Rust cache
        uses: Swatinem/rust-cache@v2
        with:
          workspaces: src-tauri

      - name: Install frontend dependencies
        run: pnpm install --frozen-lockfile

      - name: Setup Keystore (required for release)
        run: |
          echo "${{ secrets.ANDROID_KEYSTORE }}" | base64 -d > $HOME/keystore.jks
          echo "ANDROID_KEYSTORE_PATH=$HOME/keystore.jks" >> $GITHUB_ENV
          echo "ANDROID_KEYSTORE_PASSWORD=${{ secrets.ANDROID_KEYSTORE_PASSWORD }}" >> $GITHUB_ENV
          echo "ANDROID_KEY_ALIAS=${{ secrets.ANDROID_KEY_ALIAS }}" >> $GITHUB_ENV
          echo "ANDROID_KEY_PASSWORD=${{ secrets.ANDROID_KEY_PASSWORD }}" >> $GITHUB_ENV

      - name: Build Android APK and AAB (signed)
        run: pnpm tauri android build

      - name: Upload to Release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            src-tauri/gen/android/app/build/outputs/apk/**/*.apk
            src-tauri/gen/android/app/build/outputs/bundle/**/*.aab
          draft: true

  publish-release:
    permissions:
      contents: write
    runs-on: ubuntu-22.04
    needs: [create-release, build-desktop, build-android]

    steps:
      - name: Publish release
        id: publish-release
        uses: actions/github-script@v7
        env:
          release_id: ${{ needs.create-release.outputs.release_id }}
        with:
          script: |
            github.rest.repos.updateRelease({
              owner: context.repo.owner,
              repo: context.repo.repo,
              release_id: process.env.release_id,
              draft: false,
              prerelease: false
            })
