---
name: Create Release
on:
  push:
    branches:
      - main
    paths:
      - 'manwhere'
      - '.github/workflows/release.yml'

jobs:
  release:
    runs-on: self-hosted
    steps:
      - name: Get version from commit
        id: version
        run: |
          VERSION=$(git describe --tags --always --dirty 2>/dev/null || echo "v0.1.0-$(git rev-parse --short HEAD)")
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Version: $VERSION"
      
      - name: Create Release
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          
          # Delete existing release with same tag if exists
          curl -s -X DELETE \
            -H "Authorization: token $GITEA_TOKEN" \
            "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/tags/$VERSION" || true
          
          # Create new release
          curl -s -X POST \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{
              \"tag_name\": \"$VERSION\",
              \"name\": \"manwhere $VERSION\",
              \"body\": \"Release of manwhere binary\\n\\nBuilt from commit: ${{ github.sha }}\",
              \"target_commitish\": \"main\"
            }" \
            "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases" | tee release.json
          
          RELEASE_ID=$(jq -r '.id' release.json)
          
          # Upload binary
          curl -s -X POST \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/octet-stream" \
            --data-binary @manwhere \
            "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/$RELEASE_ID/assets?name=manwhere&attachment=true"
          
          echo "Release created: ${{ github.server_url }}/${{ github.repository }}/releases/tag/$VERSION"
