name: Release

on:
  push:
    tags:
      - 'v*'

permissions:
  contents: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version: '1.22'

      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'

      - name: Build binaries
        run: |
          mkdir -p dist
          VERSION=${GITHUB_REF#refs/tags/v}
          MODULE="github.com/gitlink-org/gitlink-cli"
          LDFLAGS="-s -w -X ${MODULE}/cmd.Version=${VERSION}"

          for pair in \
            "darwin amd64" \
            "darwin arm64" \
            "linux amd64" \
            "linux arm64" \
            "windows amd64" \
            "windows arm64"; do
            GOOS=$(echo "$pair" | cut -d' ' -f1)
            GOARCH=$(echo "$pair" | cut -d' ' -f2)
            OUT="gitlink-cli"
            if [ "$GOOS" = "windows" ]; then
              OUT="gitlink-cli.exe"
            fi

            echo "Building ${GOOS}-${GOARCH}..."
            BUILD_DIR="dist/gitlink-cli_${VERSION}_${GOOS}_${GOARCH}"
            mkdir -p "$BUILD_DIR"
            CGO_ENABLED=0 GOOS=$GOOS GOARCH=$GOARCH go build -ldflags "$LDFLAGS" -o "$BUILD_DIR/$OUT" .

            if [ "$GOOS" = "windows" ]; then
              (cd "$BUILD_DIR" && zip -q "../gitlink-cli_${VERSION}_${GOOS}_${GOARCH}.zip" "$OUT")
            else
              tar -czf "dist/gitlink-cli_${VERSION}_${GOOS}_${GOARCH}.tar.gz" -C "$BUILD_DIR" "$OUT"
            fi
            rm -rf "$BUILD_DIR"
          done

          ls -lh dist

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            dist/*.tar.gz
            dist/*.zip
          generate_release_notes: true

      - name: Build npm package
        run: |
          VERSION=${GITHUB_REF#refs/tags/v}
          export VERSION
          rm -rf npm-pkg
          mkdir -p npm-pkg
          cp -R npm/. npm-pkg/
          cp README.md npm-pkg/README.md
          rm -rf npm-pkg/skills
          cp -R skills npm-pkg/skills

          node <<'NODE'
          const fs = require('fs');
          const pkgPath = 'npm-pkg/package.json';
          const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
          pkg.version = process.env.VERSION;
          fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
          NODE

          chmod +x npm-pkg/bin/cli.js
          chmod +x npm-pkg/bin/install-skills.js

          cd npm-pkg
          npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
