name: Release

on:
  push:
    tags:
      - 'v*'

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

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version-file: 'go.mod'

      - name: Build
        run: CGO_ENABLED=0 go build -ldflags="-s -w" -o snitch .

      - name: Create Release
        env:
          GITEATOKEN: ${{ secrets.GITEATOKEN }}
        run: |
          VERSION="${{ github.ref_name }}"
          VER="${VERSION#v}"
          
          # Package binary
          tar czf "snitch_${VER}_linux_amd64.tar.gz" snitch
          
          # Create release
          RELEASE_ID=$(curl -s -X POST "https://gitea.bitua.io/api/v1/repos/bitua/snitch/releases" \
            -H "Authorization: token ${GITEATOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"tag_name\": \"${VERSION}\", \"name\": \"${VERSION}\"}" | jq -r .id)
          
          if [ "$RELEASE_ID" = "null" ] || [ -z "$RELEASE_ID" ]; then
            echo "Failed to create release"
            exit 1
          fi
          
          echo "Created release ID: $RELEASE_ID"
          
          # Upload asset
          curl -s -X POST "https://gitea.bitua.io/api/v1/repos/bitua/snitch/releases/${RELEASE_ID}/assets?name=snitch_${VER}_linux_amd64.tar.gz" \
            -H "Authorization: token ${GITEATOKEN}" \
            -F "attachment=@snitch_${VER}_linux_amd64.tar.gz"
          
          echo "Release ${VERSION} complete!"
