# ______   _______   _
#|  ____| |__   __| | |
#| |__       | |    | |        ___    __ _    __ _    ___   _   _
#|  __|      | |    | |       / _ \  / _` |  / _` |  / __| | | | |
#| |____     | |    | |____  |  __/ | (_| | | (_| | | (__  | |_| |
#|______|    |_|    |______|  \___|  \__, |  \__,_|  \___|  \__, |
#                                     __/ |                  __/ |
#                                    |___/                  |___/
name: CI

on:
  pull_request:
    branches: [master]
    types: [opened, synchronize, reopened]
  push:
    branches: [master]

# cancel previous unfinished/running jobs in each separate branch
concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true

jobs:
  pre-build:
    runs-on: ubuntu-latest
    outputs:
      describe: ${{ steps.git.outputs.describe }}
      tag: ${{ steps.git.outputs.tag }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          fetch-tags: true

      - uses: prefix-dev/setup-pixi@v0.8.3
        with:
          pixi-version: v0.41.4
          cache: true

      - name: Check changes
        run: |
          pixi run check-changes --github "origin/master"

      - name: Fetch git version information
        id: git
        run: |
          git fetch --tags --force
          git_describe=$(git describe --abbrev=7 2>/dev/null | awk '{$1=$1};1')
          git_tag=$(git describe --abbrev=0 2>/dev/null | awk '{$1=$1};1')
          echo "Version info: $git_describe ?? $git_tag"
          echo "describe=$git_describe" >> "$GITHUB_OUTPUT"
          echo "tag=$git_tag" >> "$GITHUB_OUTPUT"

  # Run the build on all the current platforms
  #
  # etlegacy/lnx-build:latest ships an older glibc, so JS-based actions (like actions/checkout)
  # cannot run inside the job container (node20 fails to start).
  #
  # Therefore these jobs use a pure `git` checkout step instead of `uses: actions/checkout`.
  lnx64:
    runs-on: ubuntu-24.04
    needs: [pre-build]
    container:
      image: etlegacy/lnx-build:latest
      options: --user 1001:1001
    env:
      CI_ETL_DESCRIBE: ${{ needs.pre-build.outputs.describe }}
      CI_ETL_TAG: ${{ needs.pre-build.outputs.tag }}
      CI: "true"
      GITHUB_TOKEN: ${{ github.token }}
    steps:
      - name: Checkout (git, no JS actions)
        shell: bash
        run: |
          set -euo pipefail

          git config --global --add safe.directory "$GITHUB_WORKSPACE"

          # Make submodules work even if they use https://github.com/, git://github.com/, or ssh
          git config --global url."https://x-access-token:${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/"
          git config --global url."https://x-access-token:${GITHUB_TOKEN}@github.com/".insteadOf "git://github.com/"
          git config --global url."https://x-access-token:${GITHUB_TOKEN}@github.com/".insteadOf "ssh://git@github.com/"
          git config --global url."https://x-access-token:${GITHUB_TOKEN}@github.com/".insteadOf "git@github.com:"

          # Ensure workspace is empty
          mkdir -p "$GITHUB_WORKSPACE"
          find "$GITHUB_WORKSPACE" -mindepth 1 -maxdepth 1 -exec rm -rf {} +

          cd "$GITHUB_WORKSPACE"
          git init
          git remote add origin "https://github.com/${GITHUB_REPOSITORY}.git"

          # Works for push (refs/heads/...) and PR (refs/pull/.../merge)
          git fetch --no-tags --prune --depth=1 origin "${GITHUB_REF}"
          git checkout --detach FETCH_HEAD

          git submodule sync --recursive
          git submodule update --init --recursive --depth 1 || git submodule update --init --recursive

      - name: Build
        run: |
          ./easybuild.sh build -64

      - name: Generate packages
        working-directory: build
        run: cpack

  lnx32:
    runs-on: ubuntu-24.04
    needs: [pre-build]
    container:
      image: etlegacy/lnx-build:latest
      options: --user 1001:1001
    env:
      CI_ETL_DESCRIBE: ${{ needs.pre-build.outputs.describe }}
      CI_ETL_TAG: ${{ needs.pre-build.outputs.tag }}
      CI: "true"
      GITHUB_TOKEN: ${{ github.token }}
    steps:
      - name: Checkout (git, no JS actions)
        shell: bash
        run: |
          set -euo pipefail

          git config --global --add safe.directory "$GITHUB_WORKSPACE"

          # Make submodules work even if they use https://github.com/, git://github.com/, or ssh
          git config --global url."https://x-access-token:${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/"
          git config --global url."https://x-access-token:${GITHUB_TOKEN}@github.com/".insteadOf "git://github.com/"
          git config --global url."https://x-access-token:${GITHUB_TOKEN}@github.com/".insteadOf "ssh://git@github.com/"
          git config --global url."https://x-access-token:${GITHUB_TOKEN}@github.com/".insteadOf "git@github.com:"

          # Ensure workspace is empty
          mkdir -p "$GITHUB_WORKSPACE"
          find "$GITHUB_WORKSPACE" -mindepth 1 -maxdepth 1 -exec rm -rf {} +

          cd "$GITHUB_WORKSPACE"
          git init
          git remote add origin "https://github.com/${GITHUB_REPOSITORY}.git"

          # Works for push (refs/heads/...) and PR (refs/pull/.../merge)
          git fetch --no-tags --prune --depth=1 origin "${GITHUB_REF}"
          git checkout --detach FETCH_HEAD

          git submodule sync --recursive
          git submodule update --init --recursive --depth 1 || git submodule update --init --recursive

      - name: Build
        run: |
          ./easybuild.sh build -32

      - name: Generate packages
        working-directory: build
        run: cpack

  lnx-aarch64:
    runs-on: ubuntu-latest
    needs: [pre-build]
    container:
      image: etlegacy/lnx-aarch64-build
    env:
      CI_ETL_DESCRIBE: ${{ needs.pre-build.outputs.describe }}
      CI_ETL_TAG: ${{ needs.pre-build.outputs.tag }}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        run: |
          ./easybuild.sh build -RPIT -ninja

      - name: Generate packages
        shell: bash
        working-directory: build
        run: cpack

  osx:
    runs-on: macos-14
    needs: [pre-build]
    env:
      CI_ETL_DESCRIBE: ${{ needs.pre-build.outputs.describe }}
      CI_ETL_TAG: ${{ needs.pre-build.outputs.tag }}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Install dependencies
        run: |
          brew bundle
          brew install freetype librsvg graphicsmagick imagemagick

      - name: Build
        env:
          SDKROOT: /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk
          DEVELOPER_DIR: /Library/Developer/CommandLineTools
        shell: bash
        run: |
          ./easybuild.sh build -64 --osx=10.10 --osx-arc="x86_64;arm64" -j

      - name: Generate packages
        shell: bash
        run: ./easybuild.sh package -64 --osx=10.10 --osx-arc="x86_64;arm64" -j

  win:
    runs-on: windows-2022
    needs: [pre-build]
    env:
      CI_ETL_DESCRIBE: ${{ needs.pre-build.outputs.describe }}
      CI_ETL_TAG: ${{ needs.pre-build.outputs.tag }}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        shell: cmd
        run: |
          call .\easybuild.bat build

      - name: Generate packages
        shell: cmd
        working-directory: build
        run: cpack

  win64:
    runs-on: windows-2022
    needs: [pre-build]
    env:
      CI_ETL_DESCRIBE: ${{ needs.pre-build.outputs.describe }}
      CI_ETL_TAG: ${{ needs.pre-build.outputs.tag }}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        shell: cmd
        run: |
          call .\easybuild.bat build -64

      - name: Generate packages
        shell: cmd
        working-directory: build
        run: cpack

  android:
    runs-on: ubuntu-24.04
    env:
      CI_ETL_DESCRIBE: ${{ needs.pre-build.outputs.describe }}
      CI_ETL_TAG: ${{ needs.pre-build.outputs.tag }}
    needs: [pre-build]
    container:
      image: etlegacy/android-build
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

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

      - name: Build JoyStick Dependency
        working-directory: ./app/libs/joystick
        run: |
          ./gradlew clean               --stacktrace --info
          ./gradlew assembleRelease     --stacktrace --info
          ./gradlew publishToMavenLocal --stacktrace --info

      - name: Build and Generate Package
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          ./gradlew clean assembleDebug
          ls -R

      - name: Rename APK
        run: |
          for FILE in ./app/build/outputs/apk/debug/*; do mv "$FILE" "${FILE%-*}.apk"; done
          ls app/build/outputs/apk/debug

  check-compiler-warnings:
    runs-on: ubuntu-latest
    needs:
      - android
      - lnx-aarch64
      - lnx32
      - lnx64
      - osx
      - win
      - win64
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          fetch-tags: true

      - uses: prefix-dev/setup-pixi@v0.8.3
        with:
          pixi-version: v0.41.4
          cache: true

      - name: Collect and Check GitHub Build Logs
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # fallback
          GITHUB_REPOSITORY: ${{ github.repository }}
          GITHUB_RUN_ID: ${{ github.run_id }}
        run: |
          pixi run collect-and-check-gh-build-logs --github

  ci-discord-notify-on-failure:
    needs:
      - pre-build

      - android
      - lnx-aarch64
      - lnx32
      - lnx64
      - osx
      - win
      - win64

      - check-compiler-warnings
    if: |
      github.event_name == 'push' &&
      github.ref == 'refs/heads/master' &&
      failure()
    runs-on: ubuntu-latest
    steps:
      - name: Notify Discord
        env:
          DISCORD_WEBHOOK: ${{ secrets.LEGACY_CI_WEBHOOK }}
          COMMIT_SHA: ${{ github.sha }}
          REPO: ${{ github.repository }}
          RUN_ID: ${{ github.run_id }}
          DEVS_ROLE_ID: "260752921698762752"
        run: |
          RUN_URL="https://github.com/${REPO}/actions/runs/${RUN_ID}"

          MESSAGE="❌ **[failed on commit](<${RUN_URL}>)** \`${COMMIT_SHA}\` <@&${DEVS_ROLE_ID}>"

          curl -H "Content-Type: application/json" \
               -X POST \
               -d "{\"content\": \"$MESSAGE\", \"allowed_mentions\": {\"roles\": [\"$DEVS_ROLE_ID\"]}}" \
               "$DISCORD_WEBHOOK"
