name: Source release

on:
  push:
    tags:
      - "v*"
    branches:
      - master
  workflow_dispatch:

jobs:
  source-package:
    runs-on: ubuntu-latest
    env:
      BUILD_DIR: /tmp/mars-nwe-build
      GITEA_API: https://gitea.disconnected-by-peer.at/api/v1
      OWNER: mars_nwe
      REPO: mars-nwe

    steps:
      - name: Check out source
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          fetch-tags: true
          submodules: recursive
          token: ${{ secrets.RELEASE_TOKEN }}

      - name: Fetch tags explicitly
        run: |
          git fetch --force --tags
          echo "describe:"
          git describe --tags --exact-match || true
          echo "points-at-head:"
          git tag --points-at HEAD || true

      - name: Update submodules explicitly
        run: |
          git submodule sync --recursive
          git submodule update --init --recursive

      - name: Install build dependencies
        run: |
          apt-get update
          apt-get install -y \
            cmake \
            make \
            gcc \
            g++ \
            pkg-config \
            curl \
            jq \
            libgdbm-dev \
            libcrypt-dev \
            libpam0g-dev

      - name: Configure
        run: cmake -S . -B "$BUILD_DIR"

      - name: Build source package
        run: cmake --build "$BUILD_DIR" --target package_source

      - name: Find source tarball
        id: pkg
        run: |
          set -e

          FILE="$(find "$BUILD_DIR" -maxdepth 2 -type f -name '*.tar.bz2' | sort | head -n1)"
          test -n "$FILE"

          echo "file=$FILE" >> "$GITHUB_OUTPUT"
          echo "name=$(basename "$FILE")" >> "$GITHUB_OUTPUT"

          echo "Created: $FILE"
          tar -tjf "$FILE" > tarball-list.txt
          sed -n '1,20p' tarball-list.txt

      - name: Decide release target
        id: target
        env:
          REF_TYPE: ${{ gitea.ref_type || github.ref_type }}
          REF_NAME: ${{ gitea.ref_name || github.ref_name }}
          SHA: ${{ gitea.sha || github.sha }}
        run: |
          set -e

          if [ "$REF_TYPE" = "tag" ]; then
            echo "tag=$REF_NAME" >> "$GITHUB_OUTPUT"
            echo "name=$REF_NAME" >> "$GITHUB_OUTPUT"
            echo "prerelease=false" >> "$GITHUB_OUTPUT"
          else
            SHORT_SHA="$(printf '%s' "$SHA" | cut -c1-7)"
            echo "tag=development" >> "$GITHUB_OUTPUT"
            echo "name=development ($REF_NAME @ $SHORT_SHA)" >> "$GITHUB_OUTPUT"
            echo "prerelease=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Create or update release
        env:
          GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
          REL_TAG: ${{ steps.target.outputs.tag }}
          REL_NAME: ${{ steps.target.outputs.name }}
          REL_PRERELEASE: ${{ steps.target.outputs.prerelease }}
        run: |
          set -e

          RELEASE_JSON="$(curl -fsS \
            -H "Authorization: token ${GITEA_TOKEN}" \
            "${GITEA_API}/repos/${OWNER}/${REPO}/releases/tags/${REL_TAG}" || true)"

          if [ -z "$RELEASE_JSON" ]; then
            RELEASE_JSON="$(curl -fsS -X POST \
              -H "Authorization: token ${GITEA_TOKEN}" \
              -H "Content-Type: application/json" \
              "${GITEA_API}/repos/${OWNER}/${REPO}/releases" \
              -d "$(jq -n \
                --arg tag "$REL_TAG" \
                --arg name "$REL_NAME" \
                --argjson prerelease "$REL_PRERELEASE" \
                '{tag_name:$tag,name:$name,draft:false,prerelease:$prerelease}')" )"
          else
            RELEASE_ID="$(printf '%s' "$RELEASE_JSON" | jq -r '.id')"
            RELEASE_JSON="$(curl -fsS -X PATCH \
              -H "Authorization: token ${GITEA_TOKEN}" \
              -H "Content-Type: application/json" \
              "${GITEA_API}/repos/${OWNER}/${REPO}/releases/${RELEASE_ID}" \
              -d "$(jq -n \
                --arg tag "$REL_TAG" \
                --arg name "$REL_NAME" \
                --argjson prerelease "$REL_PRERELEASE" \
                '{tag_name:$tag,name:$name,draft:false,prerelease:$prerelease}')" )"
          fi

          echo "$RELEASE_JSON" > release.json

      - name: Delete old development assets
        if: ${{ steps.target.outputs.tag == 'development' }}
        env:
          GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
        run: |
          set -e

          RELEASE_ID="$(jq -r '.id' release.json)"

          ASSET_IDS="$(curl -fsS \
            -H "Authorization: token ${GITEA_TOKEN}" \
            "${GITEA_API}/repos/${OWNER}/${REPO}/releases/${RELEASE_ID}" \
            | jq -r '.assets[]? | .id')"

          if [ -z "$ASSET_IDS" ]; then
            echo "No old development assets to delete."
            exit 0
          fi

          for ASSET_ID in $ASSET_IDS; do
            echo "Deleting old development asset id=${ASSET_ID}"
            curl -fsS -X DELETE \
              -H "Authorization: token ${GITEA_TOKEN}" \
              "${GITEA_API}/repos/${OWNER}/${REPO}/releases/${RELEASE_ID}/assets/${ASSET_ID}"
          done

      - name: Delete old asset with same name if present
        env:
          GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
          NAME: ${{ steps.pkg.outputs.name }}
        run: |
          set -e

          RELEASE_ID="$(jq -r '.id' release.json)"
          ASSET_ID="$(curl -fsS \
            -H "Authorization: token ${GITEA_TOKEN}" \
            "${GITEA_API}/repos/${OWNER}/${REPO}/releases/${RELEASE_ID}" \
            | jq -r --arg NAME "$NAME" '.assets[]? | select(.name==$NAME) | .id' \
            | head -n1)"

          if [ -n "$ASSET_ID" ]; then
            curl -fsS -X DELETE \
              -H "Authorization: token ${GITEA_TOKEN}" \
              "${GITEA_API}/repos/${OWNER}/${REPO}/releases/${RELEASE_ID}/assets/${ASSET_ID}"
          fi

      - name: Upload tarball to release
        env:
          GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
          FILE: ${{ steps.pkg.outputs.file }}
          NAME: ${{ steps.pkg.outputs.name }}
        run: |
          set -e

          RELEASE_ID="$(jq -r '.id' release.json)"

          curl -fsS -X POST \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -H "Content-Type: application/octet-stream" \
            --data-binary @"${FILE}" \
            "${GITEA_API}/repos/${OWNER}/${REPO}/releases/${RELEASE_ID}/assets?name=${NAME}"
