name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

env:
  BIN_NAME: vcom

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version-file: go.mod
          cache: true

      - name: Run tests
        run: GOFLAGS=-mod=vendor go test ./...

  release:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version-file: go.mod
          cache: true

      - name: Install system dependencies
        run: sudo apt-get update && sudo apt-get install -y dpkg-dev

      - name: Derive release version
        shell: bash
        run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV"

      - name: Vendor Go modules
        run: go mod vendor

      - name: Build release binary
        shell: bash
        run: |
          set -euo pipefail
          mkdir -p target/release
          GOFLAGS=-mod=vendor CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o "target/release/${BIN_NAME}" ./cmd/vcom

      - name: Build deb package
        shell: bash
        run: ./scripts/build-deb.sh "${VERSION}"

      - name: Bundle tarball
        shell: bash
        run: |
          set -euo pipefail
          tar -C target/release -czf "${BIN_NAME}-${GITHUB_REF_NAME}-x86_64-unknown-linux-gnu.tar.gz" "${BIN_NAME}"

      - name: Generate checksums
        shell: bash
        run: |
          set -euo pipefail
          sha256sum \
            "${BIN_NAME}-${GITHUB_REF_NAME}-x86_64-unknown-linux-gnu.tar.gz" \
            "target/debian/${BIN_NAME}_${VERSION}_amd64.deb" \
            > "${BIN_NAME}-${GITHUB_REF_NAME}-checksums.txt"

      - name: Publish release assets
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
          files: |
            vcom-${{ github.ref_name }}-x86_64-unknown-linux-gnu.tar.gz
            vcom-${{ github.ref_name }}-checksums.txt
            target/debian/vcom_${{ env.VERSION }}_amd64.deb
