# ______   _______   _
#|  ____| |__   __| | |
#| |__       | |    | |        ___    __ _    __ _    ___   _   _
#|  __|      | |    | |       / _ \  / _` |  / _` |  / __| | | | |
#| |____     | |    | |____  |  __/ | (_| | | (_| | | (__  | |_| |
#|______|    |_|    |______|  \___|  \__, |  \__,_|  \___|  \__, |
#                                     __/ |                  __/ |
#                                    |___/                  |___/
# 2024 Legacy team
name: ETLBuild

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:
  schedule:
    - cron: "0 0 * * FRI"

jobs:
  # Try to figure out the build version information only once
  pre-build:
    runs-on: ubuntu-latest
    outputs:
      describe: ${{ steps.git.outputs.describe }}
      tag: ${{ steps.git.outputs.tag }}
      uid: ${{ steps.git.outputs.uid }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          fetch-tags: true

      - 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')
          ci_id=$(uuidgen)
          echo "Version info: $git_describe ?? $git_tag"
          {
            echo "describe=$git_describe"
            echo "tag=$git_tag"
            echo "uid=$ci_id"
          } >> "$GITHUB_OUTPUT"

  #   __  __               _                                                  _     _
  #  |  \/  |             | |                                                | |   (_)
  #  | \  / |   ___     __| |     __ _    ___   _ __     ___   _ __    __ _  | |_   _    ___    _ __
  #  | |\/| |  / _ \   / _` |    / _` |  / _ \ | '_ \   / _ \ | '__|  / _` | | __| | |  / _ \  | '_ \
  #  | |  | | | (_) | | (_| |   | (_| | |  __/ | | | | |  __/ | |    | (_| | | |_  | | | (_) | | | | |
  #  |_|  |_|  \___/   \__,_|    \__, |  \___| |_| |_|  \___| |_|     \__,_|  \__| |_|  \___/  |_| |_|
  #                               __/ |
  #                              |___/

  lnx64-mod:
    runs-on: ubuntu-24.04
    needs: pre-build
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        env:
          CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
          CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
          CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
        uses: maus007/docker-run-action-fork@v1
        with:
          image: etlegacy/lnx-build:latest
          options: -v ${{ github.workspace }}:/code -e CI_ETL_DESCRIBE=${{needs.pre-build.outputs.describe}} -e CI_ETL_TAG=${{needs.pre-build.outputs.tag}} -e CI_ETL_UID=${{needs.pre-build.outputs.uid}} -e CI=true
          run: |
            git config --global --add safe.directory /code
            ./easybuild.sh build -64 -mod

      - uses: actions/upload-artifact@v4
        with:
          name: lnx64-mod
          path: |
            build/legacy/cgame*.so
            build/legacy/ui*.so
            build/legacy/qagame*.so
            build/legacy/tvgame*.so
          if-no-files-found: error

      - uses: actions/upload-artifact@v4
        with:
          name: incomplete-mod-pk3
          path: build/legacy/legacy_*.pk3
          if-no-files-found: error

  lnx32-mod:
    runs-on: ubuntu-24.04
    needs: pre-build
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        env:
          CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
          CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
          CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
        uses: maus007/docker-run-action-fork@v1
        with:
          image: etlegacy/lnx-build:latest
          options: -v ${{ github.workspace }}:/code -e CI_ETL_DESCRIBE=${{needs.pre-build.outputs.describe}} -e CI_ETL_TAG=${{needs.pre-build.outputs.tag}} -e CI_ETL_UID=${{needs.pre-build.outputs.uid}} -e CI=true
          run: |
            git config --global --add safe.directory /code
            ./easybuild.sh build -mod

      - uses: actions/upload-artifact@v4
        with:
          name: lnx32-mod
          path: |
            build/legacy/cgame*.so
            build/legacy/ui*.so
            build/legacy/qagame*.so
            build/legacy/tvgame*.so
          if-no-files-found: error

  lnx-aarch64-mod:
    runs-on: ubuntu-24.04
    needs: pre-build
    container:
      image: etlegacy/lnx-aarch64-build
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        env:
          CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
          CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
          CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          ./easybuild.sh build -RPIT -mod -ninja

      - uses: actions/upload-artifact@v4
        with:
          name: lnx-aarch64-mod
          path: |
            build/legacy/cgame*.so
            build/legacy/ui*.so
            build/legacy/qagame*.so
            build/legacy/tvgame*.so
          if-no-files-found: error

  osx-mod:
    runs-on: macos-14
    needs: pre-build
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Install dependencies
        run: brew bundle

      - name: List dev tools
        run: |
          # shellcheck disable=SC2010
          ls -la /Applications/ | grep Xcode
          ls -la /Library/Developer/CommandLineTools/SDKs/
          xcode-select --print-path
          xcrun -sdk macosx --show-sdk-path

      - name: Build
        env:
          SDKROOT: /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk
          DEVELOPER_DIR: /Library/Developer/CommandLineTools
          CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
          CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
          CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
        shell: bash
        run: |
          ./easybuild.sh build -64 -mod --osx=10.10 --osx-arc="x86_64;arm64" -j

      - uses: actions/upload-artifact@v4
        with:
          name: osx-mod
          path: |
            build/legacy/cgame_mac
            build/legacy/ui_mac
            build/legacy/qagame_mac
            build/legacy/tvgame_mac
          if-no-files-found: error

  win-mod:
    runs-on: windows-2022
    needs: pre-build
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        shell: cmd
        env:
          CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
          CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
          CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
        run: |
          call .\easybuild.bat build -mod

      - uses: actions/upload-artifact@v4
        with:
          name: win-mod
          path: |
            build/legacy/cgame*.dll
            build/legacy/ui*.dll
            build/legacy/qagame*.dll
            build/legacy/tvgame*.dll
          if-no-files-found: error

  win64-mod:
    runs-on: windows-2022
    needs: pre-build
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        shell: cmd
        env:
          CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
          CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
          CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
        run: |
          call .\easybuild.bat build -mod -64

      - uses: actions/upload-artifact@v4
        with:
          name: win64-mod
          path: |
            build/legacy/cgame*.dll
            build/legacy/ui*.dll
            build/legacy/qagame*.dll
            build/legacy/tvgame*.dll
          if-no-files-found: error

  android-mod:
    runs-on: ubuntu-24.04
    needs: pre-build
    env:
      SIGNING_KEY_ALIAS: ${{ secrets.ANDROID_SIGN_APK_ALLIAS }}
      SIGNING_KEY_PASSWORD: ${{ secrets.ANDROID_SIGN_APK_PASS }}
      SIGNING_STORE_PASSWORD: ${{ secrets.ANDROID_SIGN_APK_PASS }}
      CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
      CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
      CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
    container:
      image: etlegacy/android-build
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true
          fetch-depth: 0

      - 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: Upload JoyStick Dependency Artifacts
        uses: actions/upload-artifact@v4
        with:
          name: android-joystick-packages
          path: "/root/.m2/repository/com/etlegacy/android/joystick/"
          if-no-files-found: error

      - name: Build Release
        if: github.repository == 'etlegacy/etlegacy'
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          ./gradlew clean assembleRelease --stacktrace --info
          ls -R
      - name: Build Debug
        if: github.repository != 'etlegacy/etlegacy'
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          ./gradlew clean assembleDebug --stacktrace --info
          ls -R

      - name: Prepare artifacts
        run: |
          mv ./app/build/intermediates/merged_native_libs/*/mergeReleaseNativeLibs/out/lib/arm64-v8a/libcgame*.so .
          mv ./app/build/intermediates/merged_native_libs/*/mergeReleaseNativeLibs/out/lib/arm64-v8a/libui*.so .
          mv ./app/build/intermediates/merged_native_libs/*/mergeReleaseNativeLibs/out/lib/x86/libcgame*.so .
          mv ./app/build/intermediates/merged_native_libs/*/mergeReleaseNativeLibs/out/lib/x86/libui*.so .
          mv ./app/build/intermediates/merged_native_libs/*/mergeReleaseNativeLibs/out/lib/x86_64/libcgame*.so .
          mv ./app/build/intermediates/merged_native_libs/*/mergeReleaseNativeLibs/out/lib/x86_64/libui*.so .
          ls -ltrah

      - name: Upload arm64-v8a
        uses: actions/upload-artifact@v4
        with:
          name: android-arm64-mod
          path: |
            libcgame*arm64*.so
            libui*arm64*.so
          if-no-files-found: error

      - name: Upload x86
        uses: actions/upload-artifact@v4
        with:
          name: android-x86-mod
          path: |
            libcgame*i386.so
            libui*i386.so
          if-no-files-found: error

      - name: Upload x86_64
        uses: actions/upload-artifact@v4
        with:
          name: android-x86_64-mod
          path: |
            libcgame*x86_64.so
            libui*x86_64.so
          if-no-files-found: error

  #   __  __                                                          _
  #  |  \/  |                                                        | |
  #  | \  / |   ___   _ __    __ _    ___     _ __ ___     ___     __| |  ___
  #  | |\/| |  / _ \ | '__|  / _` |  / _ \   | '_ ` _ \   / _ \   / _` | / __|
  #  | |  | | |  __/ | |    | (_| | |  __/   | | | | | | | (_) | | (_| | \__ \
  #  |_|  |_|  \___| |_|     \__, |  \___|   |_| |_| |_|  \___/   \__,_| |___/
  #                           __/ |
  #                          |___/
  # Since lnx32 is installing the most, use it as the step that combines all the other steps mod files.
  # This step also generates the final packages for 32 bit lnx.
  mod-merger:
    runs-on: ubuntu-24.04
    needs: [ pre-build, lnx64-mod, lnx32-mod, osx-mod, win-mod, win64-mod, lnx-aarch64-mod, android-mod ]
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: incomplete-mod-pk3

      - uses: actions/download-artifact@v4
        with:
          pattern: "*-mod"
          path: platforms
          merge-multiple: true

      - name: Create supported platform manifest
        shell: bash
        run: |
          echo "win_x86 win_x86_64 lnx_x86 lnx_x86_64 macos_x86_64 macos_aarch64 lnx_armv8_64 android_aarch64 android_x86 android_x86_64" > platforms.manifest

      - name: Merge mod files
        shell: bash
        run: |
          zip -rvj -MM legacy_*.pk3 platforms.manifest platforms/cgame* platforms/ui* platforms/libcgame* platforms/libui*

      - name: Create mod zip
        shell: bash
        run: |
          zip -rvj -MM etlegacy-mod-${{needs.pre-build.outputs.describe}}.zip legacy_*.pk3 platforms/qagame* platforms/tvgame*

      - name: Remove old artifacts
        uses: geekyeggo/delete-artifact@v4
        with:
          failOnError: false
          name: |
            incomplete-mod-pk3
            *-mod

      - uses: actions/upload-artifact@v4
        with:
          name: All-mods
          path: legacy_*.pk3
          if-no-files-found: error

      - uses: actions/upload-artifact@v4
        with:
          name: mod-zip
          path: etlegacy-mod-*.zip
          if-no-files-found: error

  #   ______   _                   _                            _
  #  |  ____| (_)                 | |                          | |
  #  | |__     _   _ __     __ _  | |    _ __     __ _    ___  | | __   __ _    __ _    ___   ___
  #  |  __|   | | | '_ \   / _` | | |   | '_ \   / _` |  / __| | |/ /  / _` |  / _` |  / _ \ / __|
  #  | |      | | | | | | | (_| | | |   | |_) | | (_| | | (__  |   <  | (_| | | (_| | |  __/ \__ \
  #  |_|      |_| |_| |_|  \__,_| |_|   | .__/   \__,_|  \___| |_|\_\  \__,_|  \__, |  \___| |___/
  #                                     | |                                     __/ |
  #                                     |_|                                    |___/
  # Generate the final packages for Lnx, macOS, Windows and Android
  lnx64:
    runs-on: ubuntu-24.04
    needs: [ pre-build, mod-merger ]
    env:
      CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
      CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
      CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        uses: maus007/docker-run-action-fork@v1
        with:
          image: etlegacy/lnx-build:latest
          options: -v ${{ github.workspace }}:/code -e CI_ETL_DESCRIBE=${{needs.pre-build.outputs.describe}} -e CI_ETL_TAG=${{needs.pre-build.outputs.tag}} -e CI_ETL_UID=${{needs.pre-build.outputs.uid}} -e CI=true
          run: |
            git config --global --add safe.directory /code
            ./easybuild.sh build -64

      - name: Change Owner of Container Working Directory
        run: |
          action_name=$(whoami)
          action_group=$(groups "$action_name" | awk '{print $3}')
          sudo chown "${action_name}:${action_group}" -R .

      - uses: actions/download-artifact@v4
        with:
          name: All-mods
          path: build/legacy

      - name: Display structure of downloaded files
        run: ls -R
        working-directory: build/legacy

      - name: Generate packages
        uses: maus007/docker-run-action-fork@v1
        with:
          image: etlegacy/lnx-build:latest
          options: -v ${{ github.workspace }}:/code -e CI_ETL_DESCRIBE=${{needs.pre-build.outputs.describe}} -e CI_ETL_TAG=${{needs.pre-build.outputs.tag}} -e CI=true
          run: |
            cd build/
            cpack

      - uses: actions/upload-artifact@v4
        with:
          name: lnx64-packages
          path: |
            build/etlegacy-*.tar.gz
            build/etlegacy-*.sh
          if-no-files-found: error

  lnx32:
    runs-on: ubuntu-24.04
    needs: [pre-build, mod-merger]
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Build
        uses: maus007/docker-run-action-fork@v1
        with:
          image: etlegacy/lnx-build:latest
          options: -v ${{ github.workspace }}:/code -e CI_ETL_DESCRIBE=${{needs.pre-build.outputs.describe}} -e CI_ETL_TAG=${{needs.pre-build.outputs.tag}} -e CI_ETL_UID=${{needs.pre-build.outputs.uid}} -e CI=true
          run: |
            git config --global --add safe.directory /code
            ./easybuild.sh build -32

      - name: Change Owner of Container Working Directory
        run: |
          action_name=$(whoami)
          action_group=$(groups "$action_name" | awk '{print $3}')
          sudo chown "${action_name}:${action_group}" -R .

      - uses: actions/download-artifact@v4
        with:
          name: All-mods
          path: build/legacy

      - name: Display structure of downloaded files
        run: ls -R
        working-directory: build/legacy

      - name: Generate packages
        uses: maus007/docker-run-action-fork@v1
        with:
          image: etlegacy/lnx-build:latest
          options: -v ${{ github.workspace }}:/code -e CI_ETL_DESCRIBE=${{needs.pre-build.outputs.describe}} -e CI_ETL_TAG=${{needs.pre-build.outputs.tag}} -e CI=true
          run: |
            cd build/
            cpack

      - uses: actions/upload-artifact@v4
        with:
          name: lnx32-packages
          path: |
            build/etlegacy-*.tar.gz
            build/etlegacy-*.sh
          if-no-files-found: error

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

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

      - uses: actions/download-artifact@v4
        with:
          name: All-mods
          path: build/legacy

      - name: Display structure of downloaded files
        run: ls -R
        working-directory: build/legacy

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

      - uses: actions/upload-artifact@v4
        with:
          name: lnx-aarch64-packages
          path: |
            build/etlegacy-*.tar.gz
            build/etlegacy-*.sh
          if-no-files-found: error

  osx:
    runs-on: macos-14
    needs: [pre-build, mod-merger]
    env:
      CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
      CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
      CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
    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

      - uses: actions/download-artifact@v4
        with:
          name: All-mods
          path: build/legacy

      - name: Display structure of downloaded files
        run: ls -R
        working-directory: build/legacy

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

      - uses: actions/upload-artifact@v4
        with:
          name: osx-packages
          path: |
            build/etlegacy-*.tar.gz
            build/etlegacy-*.dmg
          if-no-files-found: error

  win:
    runs-on: windows-2022
    needs: [pre-build, mod-merger]
    outputs:
      win: ${{ steps.artifact-upload-step.outputs.artifact-id }}
    env:
      CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
      CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
      CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

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

      - uses: actions/download-artifact@v4
        with:
          name: All-mods
          path: build/legacy

      - name: Display structure of downloaded files
        run: dir
        working-directory: build/legacy

      - name: Upload Win etl.exe
        uses: actions/upload-artifact@v4
        id: artifact-exe-upload-step
        with:
          name: win-exe
          path: |
            build/etl.exe
          if-no-files-found: error

      - name: SignPath Win Exe Snapshot
        uses: signpath/github-action-submit-signing-request@v1.3
        with:
          api-token: "${{ secrets.SIGNPATH_API_TOKEN }}"
          organization-id: "${{ secrets.SIGNPATH_ORGANIZATION_ID }}"
          project-slug: "etlegacy"
          signing-policy-slug: "test-signing"
          github-artifact-id: "${{steps.artifact-exe-upload-step.outputs.artifact-id}}"
          wait-for-completion: true
          output-artifact-directory: "win-exe"

      - name: SignPath Win Exe Release
        uses: signpath/github-action-submit-signing-request@v1.3
        if: github.ref_type == 'tag'
        with:
          api-token: "${{ secrets.SIGNPATH_API_TOKEN }}"
          organization-id: "${{ secrets.SIGNPATH_ORGANIZATION_ID }}"
          project-slug: "etlegacy"
          signing-policy-slug: "release-signing"
          github-artifact-id: "${{steps.artifact-exe-upload-step.outputs.artifact-id}}"
          wait-for-completion: true
          output-artifact-directory: "win-exe"

      - name: Generate packages
        shell: cmd
        working-directory: build
        run: |
          cp D:\a\etlegacy\etlegacy\win-exe\etl.exe .
          cpack

      - uses: actions/upload-artifact@v4
        id: artifact-upload-step
        with:
          name: win-packages
          path: |
            build/etlegacy-*.exe
            build/etlegacy-*.zip
          if-no-files-found: error

  win64:
    runs-on: windows-2022
    needs: [pre-build, mod-merger]
    outputs:
      win64: ${{ steps.artifact-upload-step.outputs.artifact-id }}
    env:
      CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
      CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
      CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

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

      - uses: actions/download-artifact@v4
        with:
          name: All-mods
          path: build/legacy

      - name: Display structure of downloaded files
        run: dir
        working-directory: build/legacy

      - name: Upload Win64 etl.exe
        uses: actions/upload-artifact@v4
        id: artifact-exe-upload-step
        with:
          name: win64-exe
          path: |
            build/etl.exe
          if-no-files-found: error

      - name: SignPath Win64 Exe Snapshot
        uses: signpath/github-action-submit-signing-request@v1.3
        with:
          api-token: "${{ secrets.SIGNPATH_API_TOKEN }}"
          organization-id: "${{ secrets.SIGNPATH_ORGANIZATION_ID }}"
          project-slug: "etlegacy"
          signing-policy-slug: "test-signing"
          github-artifact-id: "${{steps.artifact-exe-upload-step.outputs.artifact-id}}"
          wait-for-completion: true
          output-artifact-directory: "win64-exe"

      - name: SignPath Win64 Exe Release
        uses: signpath/github-action-submit-signing-request@v1.3
        if: github.ref_type == 'tag'
        with:
          api-token: "${{ secrets.SIGNPATH_API_TOKEN }}"
          organization-id: "${{ secrets.SIGNPATH_ORGANIZATION_ID }}"
          project-slug: "etlegacy"
          signing-policy-slug: "release-signing"
          github-artifact-id: "${{steps.artifact-exe-upload-step.outputs.artifact-id}}"
          wait-for-completion: true
          output-artifact-directory: "win64-exe"

      - name: Generate packages
        shell: cmd
        working-directory: build
        run: |
          cp D:\a\etlegacy\etlegacy\win64-exe\etl.exe .
          cpack

      - uses: actions/upload-artifact@v4
        id: artifact-upload-step
        with:
          name: win64-packages
          path: |
            build/etlegacy-*.exe
            build/etlegacy-*.zip
          if-no-files-found: error

  android:
    runs-on: ubuntu-24.04
    env:
      SIGNING_KEY_ALIAS: ${{ secrets.ANDROID_SIGN_APK_ALLIAS }}
      SIGNING_KEY_PASSWORD: ${{ secrets.ANDROID_SIGN_APK_PASS }}
      SIGNING_STORE_PASSWORD: ${{ secrets.ANDROID_SIGN_APK_PASS }}
      CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
      CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
      CI_ETL_UID: ${{needs.pre-build.outputs.uid}}
    needs: [ pre-build, mod-merger ]
    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: Download JoyStick Dependency Artifacts
        uses: actions/download-artifact@v4
        with:
          name: android-joystick-packages
          path: "/root/.m2/repository/com/etlegacy/android/joystick/"

      - uses: actions/download-artifact@v4
        with:
          name: All-mods
          path: app/src/main/assets

      - name: Display structure of downloaded files
        run: ls -R
        working-directory: app/src/main/assets

      - name: Build Release and Generate Package
        if: github.repository == 'etlegacy/etlegacy'
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          ./gradlew clean assembleRelease --stacktrace --info
          ls -R
      - name: Build Debug and Generate Package
        if: github.repository != 'etlegacy/etlegacy'
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          ./gradlew clean assembleDebug --stacktrace --info
          ls -R

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

      - uses: actions/upload-artifact@v4
        with:
          name: android-packages
          path: app/build/outputs/apk/*/etlegacy*.apk
          if-no-files-found: error

  #    ____  _             ____       _   _
  #   / ___|(_) __ _ _ __ |  _ \ __ _| |_| |__
  #   \___ \| |/ _` | '_ \| |_) / _` | __| '_ \
  #    ___) | | (_| | | | |  __/ (_| | |_| | | |
  #   |____/|_|\__, |_| |_|_|   \__,_|\__|_| |_|
  #            |___/

  sign:
    if: github.repository == 'etlegacy/etlegacy'
    runs-on: ubuntu-24.04
    needs: [pre-build, win, win64]
    steps:
      - name: Get version status
        id: vars
        run: |
          echo "hash_exists=$(curl -s -o /dev/null -w "%{http_code}" ${{ secrets.LEGACY_UPLOAD_CHECK_URL }}${{ github.sha }} 2>/dev/null)" >> "$GITHUB_OUTPUT"

      - uses: actions/download-artifact@v4
        if: ${{ steps.vars.outputs.hash_exists == '404' }}
        with:
          pattern: win*

      - name: SignPath Win Snapshot
        uses: signpath/github-action-submit-signing-request@v1.3
        if: ${{ steps.vars.outputs.hash_exists == '404' && github.ref == 'refs/heads/master' }}
        with:
          api-token: "${{ secrets.SIGNPATH_API_TOKEN }}"
          organization-id: "${{ secrets.SIGNPATH_ORGANIZATION_ID }}"
          project-slug: "etlegacy"
          signing-policy-slug: "test-signing"
          github-artifact-id: "${{needs.win.outputs.win}}"
          wait-for-completion: true
          output-artifact-directory: "win-packages"

      - name: SignPath Win64 Snapshot
        uses: signpath/github-action-submit-signing-request@v1.3
        if: ${{ steps.vars.outputs.hash_exists == '404' && github.ref == 'refs/heads/master' }}
        with:
          api-token: "${{ secrets.SIGNPATH_API_TOKEN }}"
          organization-id: "${{ secrets.SIGNPATH_ORGANIZATION_ID }}"
          project-slug: "etlegacy"
          signing-policy-slug: "test-signing"
          github-artifact-id: "${{needs.win64.outputs.win64}}"
          wait-for-completion: true
          output-artifact-directory: "win64-packages"

      - name: SignPath Win Release
        uses: signpath/github-action-submit-signing-request@v1.3
        if: github.ref_type == 'tag'
        with:
          api-token: "${{ secrets.SIGNPATH_API_TOKEN }}"
          organization-id: "${{ secrets.SIGNPATH_ORGANIZATION_ID }}"
          project-slug: "etlegacy"
          signing-policy-slug: "release-signing"
          github-artifact-id: "${{needs.win.outputs.win}}"
          wait-for-completion: true
          output-artifact-directory: "win-packages"

      - name: SignPath Win64 Release
        uses: signpath/github-action-submit-signing-request@v1.3
        if: github.ref_type == 'tag'
        with:
          api-token: "${{ secrets.SIGNPATH_API_TOKEN }}"
          organization-id: "${{ secrets.SIGNPATH_ORGANIZATION_ID }}"
          project-slug: "etlegacy"
          signing-policy-slug: "release-signing"
          github-artifact-id: "${{needs.win64.outputs.win64}}"
          wait-for-completion: true
          output-artifact-directory: "win64-packages"

      - uses: actions/upload-artifact@v4
        if: ${{ steps.vars.outputs.hash_exists == '404' }}
        with:
          name: win-packages
          path: |
            win-packages/etlegacy-*-x86.exe
            win-packages/etlegacy-*-x86.zip
          overwrite: true
          if-no-files-found: error

      - uses: actions/upload-artifact@v4
        if: ${{ steps.vars.outputs.hash_exists == '404' }}
        with:
          name: win64-packages
          path: |
            win64-packages/etlegacy-*-x64.exe
            win64-packages/etlegacy-*-x64.zip
          overwrite: true
          if-no-files-found: error

  #   _    _           _                       _                         _      _____   _
  #  | |  | |         | |                     | |                       | |    / ____| | |
  #  | |  | |  _ __   | |   ___     __ _    __| |     __ _   _ __     __| |   | |      | |   ___    __ _   _ __    _   _   _ __
  #  | |  | | | '_ \  | |  / _ \   / _` |  / _` |    / _` | | '_ \   / _` |   | |      | |  / _ \  / _` | | '_ \  | | | | | '_ \
  #  | |__| | | |_) | | | | (_) | | (_| | | (_| |   | (_| | | | | | | (_| |   | |____  | | |  __/ | (_| | | | | | | |_| | | |_) |
  #   \____/  | .__/  |_|  \___/   \__,_|  \__,_|    \__,_| |_| |_|  \__,_|    \_____| |_|  \___|  \__,_| |_| |_|  \__,_| | .__/
  #           | |                                                                                                         | |
  #           |_|                                                                                                         |_|

  upload:
    runs-on: ubuntu-24.04
    needs: [pre-build, sign, lnx32, lnx64, osx, lnx-aarch64, android]
    if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')
    steps:
      - uses: geekyeggo/delete-artifact@v4
        with:
          name: |
            All-mods

      - name: Get version status
        id: vars
        run: |
          echo "hash_exists=$(curl -s -o /dev/null -w "%{http_code}" ${{ secrets.LEGACY_UPLOAD_CHECK_URL }}${{ github.sha }} 2>/dev/null)" >> "$GITHUB_OUTPUT"

      - uses: actions/download-artifact@v4
        if: ${{ steps.vars.outputs.hash_exists == '404' }}
        with:
          path: packages

      - name: Register version
        if: ${{ steps.vars.outputs.hash_exists == '404' }}
        run: |
          curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -F"sha=${{ github.sha }}" -F"uid=${{needs.pre-build.outputs.uid}}" -F"desc=${{needs.pre-build.outputs.describe}}" ${{ secrets.LEGACY_VERSION_REGISTER_URL }}

      - name: Upload packages
        if: ${{ steps.vars.outputs.hash_exists == '404' }}
        shell: bash
        working-directory: packages
        run: |
          find lnx64-packages/ -name '*' -type f -exec curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -H "Content-Type: multipart/form-data" -F "data=@{}" -F "upload_id=ouJ8LoD4tpFE" -F"sha=${{ github.sha }}" ${{ secrets.LEGACY_UPLOAD_URL }} \;
          find lnx32-packages/ -name '*' -type f -exec curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -H "Content-Type: multipart/form-data" -F "data=@{}" -F "upload_id=3Eib0F0HiVcY" -F"sha=${{ github.sha }}" ${{ secrets.LEGACY_UPLOAD_URL }} \;
          find osx-packages/ -name '*' -type f -exec curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -H "Content-Type: multipart/form-data" -F "data=@{}" -F "upload_id=zrm0gXDJ0vvQ" -F"sha=${{ github.sha }}" ${{ secrets.LEGACY_UPLOAD_URL }} \;
          find win-packages/ -name '*' -type f -exec curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -H "Content-Type: multipart/form-data" -F "data=@{}" -F "upload_id=qkKkqKmiKHul" -F"sha=${{ github.sha }}" ${{ secrets.LEGACY_UPLOAD_URL }} \;
          find win64-packages/ -name '*' -type f -exec curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -H "Content-Type: multipart/form-data" -F "data=@{}" -F "upload_id=1EM7l2e6pqpA" -F"sha=${{ github.sha }}" ${{ secrets.LEGACY_UPLOAD_URL }} \;
          find android-packages/ -name '*' -type f -exec curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -H "Content-Type: multipart/form-data" -F "data=@{}" -F "upload_id=pqxx51ioaosg" -F"sha=${{ github.sha }}" ${{ secrets.LEGACY_UPLOAD_URL }} \;
          find lnx-aarch64-packages/ -name '*' -type f -exec curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -H "Content-Type: multipart/form-data" -F "data=@{}" -F "upload_id=r3tqepamenlf" -F"sha=${{ github.sha }}" ${{ secrets.LEGACY_UPLOAD_URL }} \;
          find mod-zip/ -name '*' -type f -exec curl --fail -H "Authorization: Bearer ${{ secrets.LEGACY_AUTH }}" -X POST -H "Content-Type: multipart/form-data" -F "data=@{}" -F "upload_id=eacan4jn14wt" -F"sha=${{ github.sha }}" ${{ secrets.LEGACY_UPLOAD_URL }} \;

      - name: Discord notification
        if: ${{ steps.vars.outputs.hash_exists == '404' && needs.pre-build.outputs.describe != needs.pre-build.outputs.tag }}
        env:
          DISCORD_WEBHOOK: ${{ secrets.PUBLISH_DISCORD_WEBHOOK }}
        uses: Ilshidur/action-discord@0.3.0
        with:
          args: "<@&673533235887865879> Build from ETLegacy: ${{ needs.pre-build.outputs.describe }} (${{ github.sha }}) has been published.\nDownload at: https://www.etlegacy.com/workflow-files"

  docker:
    runs-on: ubuntu-24.04
    needs: [pre-build, upload] # only upload to docker if the upload to the site was successfully completed
    # only run on master
    if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')
    env:
      CI_ETL_DESCRIBE: ${{needs.pre-build.outputs.describe}}
      CI_ETL_TAG: ${{needs.pre-build.outputs.tag}}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: false

      - uses: actions/download-artifact@v4
        with:
          name: lnx64-packages
          path: build/package

      - name: Setup folder
        working-directory: build/package
        run: |
          cp ../../misc/docker/dedicated.Dockerfile ./Dockerfile
          cp ../../misc/docker/entrypoint.sh ./entrypoint.sh

      - name: Package folder contents
        working-directory: build/package
        run: |
          ls -R

      - name: Login to DockerHub Registry
        run: echo ${{ secrets.DOCKERHUB_PASSWORD }} | docker login -u ${{ secrets.DOCKERHUB_USERNAME }} --password-stdin

      - name: Get the version
        id: vars
        run: |
          tag_missing=$(docker manifest inspect "etlegacy/server:${CI_ETL_DESCRIBE}" > /dev/null ; echo $?)
          echo "Current tag ${{needs.pre-build.outputs.describe}} is missing from Docker: $tag_missing"
          echo "tag_missing=$tag_missing" >> "$GITHUB_OUTPUT"

      # If we are on any build version then we create the latest-patch version
      - name: Build the server container
        working-directory: build/package
        run: |
          docker build . --file Dockerfile --tag etlegacy/server:latest-patch
          docker push etlegacy/server:latest-patch

      # Create weekly tag when scheduled and update when triggered on docker hub
      - name: Build and push the weekly Docker image
        if: ${{ github.event_name == 'schedule' }}
        working-directory: build/package
        run: |
          docker tag etlegacy/server:latest-patch etlegacy/server:weekly
          docker push etlegacy/server:weekly

      # If we are on a release tag, then also create the 'latest' tag on docker hub
      - name: Build and push the latest Docker image
        if: needs.pre-build.outputs.describe == needs.pre-build.outputs.tag && steps.vars.outputs.tag_missing == '1' && github.event_name != 'schedule'
        working-directory: build/package
        run: |
          docker tag etlegacy/server:latest-patch "etlegacy/server:${CI_ETL_DESCRIBE}"
          docker tag etlegacy/server:latest-patch "etlegacy/server:latest"
          docker push "etlegacy/server:${CI_ETL_DESCRIBE}"
          docker push "etlegacy/server:latest"

  cleanup:
    runs-on: ubuntu-24.04
    if: always()
    needs: [upload, docker]
    steps:
      - uses: geekyeggo/delete-artifact@v4
        with:
          failOnError: false
          name: |
            All-mods
            mod-zip
            incomplete-mod-pk3
            *-packages
            *-mod
            *-exe

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

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

      - mod-merger

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

      - sign

      - upload
      - docker
      - cleanup
    if: |
      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="❌ ETLBuild **[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"
