name: SPT-Server Nightly

on:
  schedule:
    - cron: '30 2 * * *'
  push:
    paths:
      - '.github/workflows/build-nightly-cron.yaml'

env:
  SERVER_URL: https://github.com
  REPOSITORY_SPT_SERVER: sp-tarkov/server-csharp
  REPOSITORY_SPT_SERVER_AIRRYCO: AirryCo/spt-server
  NIGHTLY_BRANCH: develop

jobs:
  prepare:
    runs-on: ubuntu-latest
    outputs:
      PROCEED: ${{ steps.compare-hash.outputs.PROCEED }}
      PROCEED_FIKA: ${{ steps.compare-fika.outputs.PROCEED }}
      BUILT_HASH: ${{ steps.compare-hash.outputs.BUILT_HASH }}
      CLIENT_VERSION: ${{ steps.versions.outputs.CLIENT_VERSION }}
      SPT_VERSION: ${{ steps.versions.outputs.SPT_VERSION }}
      SPT_COMMIT_ID: ${{ steps.versions.outputs.SPT_COMMIT_ID }}
      FIKA_SERVER_COMMIT: ${{ steps.compare-fika.outputs.FIKA_SERVER_COMMIT }}
      BUILD_DATE_TIME: ${{ steps.versions.outputs.DATE_TIME }}
      BUILD_TYPE: BLEEDING_EDGE_MODS

    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Get Latest Commit From SPT
        id: get-latest-commit
        run: |
          SPT_COMMIT_ID=$(git ls-remote ${{ env.SERVER_URL }}/${{ env.REPOSITORY_SPT_SERVER }}.git refs/heads/${{ env.NIGHTLY_BRANCH }} | awk '{print $1}')
          SPT_COMMIT_ID=${SPT_COMMIT_ID:0:8}
          echo "👽 SPT_COMMIT_ID = $SPT_COMMIT_ID"
          echo "SPT_COMMIT_ID=$SPT_COMMIT_ID" >> $GITHUB_OUTPUT
        shell: bash
      - name: Compare Hashes
        id: compare-hash
        run: |
          git pull
          source trigger.nightly
          server_last_built_hash=${server:0:8}
          server_latest_commit_hash=${{ steps.get-latest-commit.outputs.SPT_COMMIT_ID }}
          if [ "$server_last_built_hash" != "$server_latest_commit_hash" ]; then
            echo "✅ There is different between last-built-hash and lastest-commit-hash, continue to build."
            echo "PROCEED=true" >> $GITHUB_OUTPUT
          else
            echo "PROCEED=false" >> $GITHUB_OUTPUT
          fi
          echo "BUILT_HASH=$server_last_built_hash" >> $GITHUB_OUTPUT
        shell: bash
      - name: Extract versions
        id: versions
        if: steps.compare-hash.outputs.PROCEED == 'true'
        run: |
          SPT_COMMIT_ID=${{ steps.get-latest-commit.outputs.SPT_COMMIT_ID }}

          # Extract versions from core.json
          wget https://raw.githubusercontent.com/${{ env.REPOSITORY_SPT_SERVER }}/refs/heads/${{ env.NIGHTLY_BRANCH }}/Libraries/SPTarkov.Server.Assets/Assets/configs/core.json
          SPT_VERSION=$(jq -r '.sptVersion' core.json)
          CLIENT_VERSION=$(jq -r '.compatibleTarkovVersion' core.json)

          echo "👽 CLIENT_VERSION = $CLIENT_VERSION"
          echo "👽 SPT_VERSION = $SPT_VERSION"
          echo "👽 SPT_COMMIT_ID = $SPT_COMMIT_ID"

          echo "CLIENT_VERSION=$CLIENT_VERSION" >> $GITHUB_OUTPUT
          echo "SPT_VERSION=$SPT_VERSION" >> $GITHUB_OUTPUT
          echo "SPT_COMMIT_ID=$SPT_COMMIT_ID" >> $GITHUB_OUTPUT
          echo "DATE_TIME=$(date +%Y%m%d)" >> $GITHUB_OUTPUT
        shell: bash

  build-server-host:
    needs: prepare
    if: needs.prepare.outputs.PROCEED == 'true'
    runs-on: ubuntu-latest
    container:
      image: refringe/spt-build-dotnet:2.0.2
    outputs:
      COMMIT_ID_LONG: ${{ steps.debug-info.outputs.COMMIT_ID_LONG }}
      COMMIT_ID_SHORT: ${{ steps.debug-info.outputs.COMMIT_ID_SHORT }}
      SPT_COMMIT_TIME: ${{ steps.debug-info.outputs.SPT_COMMIT_TIME }}
      WIN_ARTIFACT: ${{ steps.filename.outputs.WIN_ARTIFACT }}
      WIN_RELEASE_FILE: ${{ steps.filename.outputs.WIN_RELEASE }}
      LINUX_ARTIFACT: ${{ steps.filename.outputs.LINUX_ARTIFACT }}
      LINUX_RELEASE_FILE: ${{ steps.filename.outputs.LINUX_RELEASE }}

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

      - name: Clone Server
        run: |
          git clone -b ${{ env.NIGHTLY_BRANCH }} --depth=1 ${{ env.SERVER_URL }}/${{ env.REPOSITORY_SPT_SERVER }}.git /snapshot
          cd /snapshot
          git lfs pull

      - name: Runner Debug Information
        id: debug-info
        run: |
          cd /snapshot
          echo "git version: $(git --version)"
          echo "git lfs version: $(git-lfs --version)"
          echo "latest commit hash: $(git rev-parse HEAD)"
          echo "last commit message:" && git log -1 --pretty=%B

          echo "COMMIT_ID_LONG=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
          echo "COMMIT_ID_SHORT=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
          echo "SPT_COMMIT_TIME"=$(git log --pretty=format:"%ai" ${{ env.NIGHTLY_BRANCH }} -1) >> $GITHUB_OUTPUT
        shell: bash

      - name: Replace Background Image
        id: bg
        run: |
          cp custom/bg.png /snapshot/Libraries/SPTarkov.Server.Assets/Assets/images/launcher/
        shell: bash

      - name: Replace projectName For Windows
        run: |
          cd /snapshot/Libraries/SPTarkov.Server.Assets/Assets/configs
          git checkout core.json
          sed -i "s/\"projectName\": \"SPT\",/\"projectName\": \"AirryCo's SPT Windows\",/g" core.json
        shell: bash

      - name: Publish Windows Server
        run: |
          cd /snapshot
          dotnet publish ./SPTarkov.Server/SPTarkov.Server.csproj -c Release -f net9.0 -r win-x64 -p:IncludeNativeLibrariesForSelfExtract=true -p:PublishSingleFile=true --self-contained false -p:SptBuildType=${{ needs.prepare.outputs.BUILD_TYPE }} -p:SptVersion=${{ needs.prepare.outputs.SPT_VERSION }} -p:SptBuildTime=$( date +%Y%m%d ) -p:SptCommit=${{ steps.debug-info.outputs.COMMIT_ID_SHORT }}
        shell: bash

      - name: Replace projectName For Linux
        run: |
          cd /snapshot/Libraries/SPTarkov.Server.Assets/Assets/configs
          git checkout core.json
          sed -i "s/\"projectName\": \"SPT\",/\"projectName\": \"AirryCo's SPT Linux\",/g" core.json
        shell: bash

      - name: Publish Linux Server
        shell: bash
        run: |
          cd /snapshot
          dotnet publish ./SPTarkov.Server/SPTarkov.Server.csproj -c Release -f net9.0 -r linux-x64 -p:IncludeNativeLibrariesForSelfExtract=true -p:PublishSingleFile=true --self-contained false -p:SptBuildType=${{ needs.prepare.outputs.BUILD_TYPE }} -p:SptVersion=${{ needs.prepare.outputs.SPT_VERSION }} -p:SptBuildTime=$( date +%Y%m%d ) -p:SptCommit=${{ steps.debug-info.outputs.COMMIT_ID_SHORT }}

      - name: Generate File Name
        id: filename
        run: |
          win_artifact_name=spt-server-${{ needs.prepare.outputs.SPT_VERSION }}-win-nightly-${{ steps.debug-info.outputs.COMMIT_ID_SHORT }}-EFT${{ needs.prepare.outputs.CLIENT_VERSION }}-${{ needs.prepare.outputs.BUILD_DATE_TIME }}-artifact
          win_release_name=spt-server-${{ needs.prepare.outputs.SPT_VERSION }}-win-nightly-${{ steps.debug-info.outputs.COMMIT_ID_SHORT }}-EFT${{ needs.prepare.outputs.CLIENT_VERSION }}-${{ needs.prepare.outputs.BUILD_DATE_TIME }}.zip
          echo "WIN_ARTIFACT=$win_artifact_name" >> $GITHUB_OUTPUT
          echo "WIN_RELEASE=$win_release_name" >> $GITHUB_OUTPUT

          linux_artifact_name=spt-server-${{ needs.prepare.outputs.SPT_VERSION }}-linux-nightly-${{ steps.debug-info.outputs.COMMIT_ID_SHORT }}-EFT${{ needs.prepare.outputs.CLIENT_VERSION }}-${{ needs.prepare.outputs.BUILD_DATE_TIME }}-artifact
          linux_release_name=spt-server-${{ needs.prepare.outputs.SPT_VERSION }}-linux-nightly-${{ steps.debug-info.outputs.COMMIT_ID_SHORT }}-EFT${{ needs.prepare.outputs.CLIENT_VERSION }}-${{ needs.prepare.outputs.BUILD_DATE_TIME }}.zip
          echo "LINUX_ARTIFACT=$linux_artifact_name" >> $GITHUB_OUTPUT
          echo "LINUX_RELEASE=$linux_release_name" >> $GITHUB_OUTPUT
        shell: bash

      - name: Artifact Windows Server
        uses: actions/upload-artifact@v4
        with:
          name: ${{ steps.filename.outputs.WIN_ARTIFACT }}
          path: |
            /snapshot/SPTarkov.Server/bin/Release/net9.0/win-x64/publish/
            !/snapshot/SPTarkov.Server/bin/Release/net9.0/win-x64/publish/**/*.pdb
          overwrite: true

      - name: Artifact Linux Server
        uses: actions/upload-artifact@v4
        with:
          name: ${{ steps.filename.outputs.LINUX_ARTIFACT }}
          path: |
            /snapshot/SPTarkov.Server/bin/Release/net9.0/linux-x64/publish/
            !/snapshot/SPTarkov.Server/bin/Release/net9.0/linux-x64/publish/**/*.pdb
          overwrite: true

  build-docker-image-multi-arch:
    needs: [prepare, build-server-host]
    runs-on: ubuntu-latest
    env:
      DOCKERHUB_USER: stblog
      DOCKERHUB_REPOSITORY: spt-server
      GHCR_USER: airryco
      GHCR_REPOSITORY: spt-server

    outputs:
      DOCKER_DIGEST_AMD64: ${{ steps.build-and-push-amd64.outputs.digest }}
      DOCKER_IMAGEID_AMD64: ${{ steps.build-and-push-amd64.outputs.imageid }}
      DOCKER_DIGEST_ARM64: ${{ steps.build-and-push-arm64.outputs.digest }}
      DOCKER_IMAGEID_ARM64: ${{ steps.build-and-push-arm64.outputs.imageid }}

    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Pull Files
        run: git pull

      # docker
      - name: Extract metadata for AMD64
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: |
            ${{ env.DOCKERHUB_USER }}/${{ env.DOCKERHUB_REPOSITORY }}
            ghcr.io/${{ env.GHCR_USER }}/${{ env.GHCR_REPOSITORY }}
            registry.cn-shenzhen.aliyuncs.com/spt-server/spt-server
          tags: |
            type=raw,value=nightly
      - name: Extract metadata for Arm64
        id: meta-arm64
        uses: docker/metadata-action@v5
        with:
          images: |
            ${{ env.DOCKERHUB_USER }}/${{ env.DOCKERHUB_REPOSITORY }}
            ghcr.io/${{ env.GHCR_USER }}/${{ env.GHCR_REPOSITORY }}
            registry.cn-shenzhen.aliyuncs.com/spt-server/spt-server
          tags: |
            type=raw,value=nightly-arm64

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      # DockerHub
      - name: Login to Dockerhub
        uses: docker/login-action@v3
        with:
          username: ${{ env.DOCKERHUB_USER }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      # GitHub Container Registry
      - name: Login to Github Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ env.GHCR_USER }}
          password: ${{ secrets.GHCR_TOKEN }}
      # Aliyun Registry
      - name: Login to Aliyun Registry
        uses: docker/login-action@v3
        with:
          registry: registry.cn-shenzhen.aliyuncs.com
          username: ${{ secrets.ALIYUN_REGISTRY_USER }}
          password: ${{ secrets.ALIYUN_REGISTRY_TOKEN }}

      - name: Build and Push For AMD64
        id: build-and-push-amd64
        uses: docker/build-push-action@v6
        with:
          context: ./docker
          file: ./docker/Dockerfile-nightly
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: |
            ${{ steps.meta.outputs.labels }}
            org.opencontainers.image.version=${{ env.NIGHTLY_BRANCH }}
            org.opencontainers.image.revision=${{ needs.build-server-host.outputs.COMMIT_ID_LONG }}
          platforms: linux/amd64
          build-args: |
            SPT_BUILD_TYPE=${{ needs.prepare.outputs.BUILD_TYPE }}
            SPT_VERSION=${{ needs.prepare.outputs.SPT_VERSION }}

      - name: Build and Push For ARM64
        id: build-and-push-arm64
        uses: docker/build-push-action@v6
        with:
          context: ./docker
          file: ./docker/Dockerfile-nightly-arm64
          push: true
          tags: ${{ steps.meta-arm64.outputs.tags }}
          labels: |
            ${{ steps.meta-arm64.outputs.labels }}
            org.opencontainers.image.version=${{ env.NIGHTLY_BRANCH }}
            org.opencontainers.image.revision=${{ needs.build-server-host.outputs.COMMIT_ID_LONG }}
          platforms: linux/arm64
          build-args: |
            SPT_BUILD_TYPE=${{ needs.prepare.outputs.BUILD_TYPE }}
            SPT_VERSION=${{ needs.prepare.outputs.SPT_VERSION }}

  update-trigger-and-push:
    needs: [prepare, build-server-host, build-docker-image-multi-arch]
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Update trigger and Push to GitHub
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "bot@stblog.com.cn"
          git pull
          rm trigger.nightly
          server=${{ needs.prepare.outputs.SPT_COMMIT_ID }}
          echo "server=$server" > trigger.nightly
          changes=$(git status --porcelain)
          if [ -n "$changes" ]; then
            git add trigger.nightly
            git commit -m "🤖 auto built spt-server: \`$server\`."
            git push
          fi
        shell: bash

  assemble-and-publish:
    needs: [prepare, build-server-host, build-docker-image-multi-arch, update-trigger-and-push]
    runs-on: ubuntu-latest

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

      - name: Download Windows Artifact
        uses: actions/download-artifact@v4
        with:
          name: ${{ needs.build-server-host.outputs.WIN_ARTIFACT }}
          path: windows

      - name: Download Linux Artifact
        uses: actions/download-artifact@v4
        with:
          name: ${{ needs.build-server-host.outputs.LINUX_ARTIFACT }}
          path: linux

      - name: Compress Releases
        id: compress-release
        run: |
          cd windows
          zip -r ../${{ needs.build-server-host.outputs.WIN_RELEASE_FILE }} *
          cd ../linux
          zip -r ../${{ needs.build-server-host.outputs.LINUX_RELEASE_FILE }} *
          ls -R ..
        shell: bash

      - name: Create Github Pre-release
        uses: softprops/action-gh-release@v2
        with:
          name: ${{ needs.prepare.outputs.BUILD_DATE_TIME }}
          tag_name: ${{ needs.prepare.outputs.BUILD_DATE_TIME }}
          prerelease: true
          body: |
            SPT: ***${{ needs.prepare.outputs.SPT_VERSION }}***

            Tarkov: ***${{ needs.prepare.outputs.CLIENT_VERSION }}***

            [SPT/Server](${{ env.SERVER_URL }}/${{ env.REPOSITORY_SPT_SERVER }}) commit hash: [${{ needs.prepare.outputs.SPT_COMMIT_ID }}](${{ env.SERVER_URL }}/${{ env.REPOSITORY_SPT_SERVER }}/tree/${{ needs.prepare.outputs.SPT_COMMIT_ID }}), commit time: **${{ needs.build-server-host.outputs.SPT_COMMIT_TIME }}**

            Build time: ***${{ needs.prepare.outputs.BUILD_DATE_TIME }}***

            **Docker Supported For linux/amd64 and linux/arm64**:

            For liunx/amd64:

            image id: `${{ needs.build-docker-image-multi-arch.outputs.DOCKER_IMAGEID_AMD64 }}`

            digest: `${{ needs.build-docker-image-multi-arch.outputs.DOCKER_DIGEST_AMD64 }}`

            ```bash
            docker pull stblog/spt-server:nightly
            docker pull ghcr.io/airryco/spt-server:nightly
            docker pull registry.cn-shenzhen.aliyuncs.com/spt-server/spt-server:nightly
            ```

            For linux/arm64:

            image id: `${{ needs.build-docker-image-multi-arch.outputs.DOCKER_IMAGEID_ARM64 }}`

            digest: `${{ needs.build-docker-image-multi-arch.outputs.DOCKER_DIGEST_ARM64 }}`

            ```bash
            docker pull stblog/spt-server:nightly-arm64
            docker pull ghcr.io/airryco/spt-server:nightly-arm64
            docker pull registry.cn-shenzhen.aliyuncs.com/spt-server/spt-server:nightly-arm64
            ```

            > [!WARNING]
            > After downloading, please use extraction software like WinRAR or [7-Zip](https://www.7-zip.org/) to unzip the files, then copy them to the Tarkov root directory. Do not use Windows File Explorer to directly open and copy the files.

            Full Changelog: [${{ needs.prepare.outputs.BUILT_HASH }}...${{ needs.prepare.outputs.SPT_COMMIT_ID }}](${{ env.SERVER_URL }}/${{ env.REPOSITORY_SPT_SERVER_AIRRYCO }}/compare/${{ needs.prepare.outputs.BUILT_HASH }}...${{ needs.prepare.outputs.SPT_COMMIT_ID }})

          files: |
            ${{ needs.build-server-host.outputs.WIN_RELEASE_FILE }}
            ${{ needs.build-server-host.outputs.LINUX_RELEASE_FILE }}
