name: Build Linux Binary

on:
  push:
    branches: [ main, master ]
    tags:
      - 'v*'
  workflow_dispatch:
    inputs:
      version:
        description: 'Version to build (leave empty for auto)'
        required: false
        type: string

permissions:
  contents: write

jobs:
  build:
    name: Build Linux Binary
    runs-on: ario-server

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.23.3'
          cache: true

      - name: Build
        env:
          CGO_ENABLED: 0
          GOOS: linux
          GOARCH: amd64
        run: |
          VERSION=${{ github.event.inputs.version }}
          if [ -z "$VERSION" ]; then
            VERSION=$(git describe --tags --always --dirty)
          fi

          echo "Building ppanel-server $VERSION"
          BUILD_TIME=$(date +"%Y-%m-%d_%H:%M:%S")
          go build -ldflags="-w -s -X github.com/perfect-panel/server/pkg/constant.Version=$VERSION -X github.com/perfect-panel/server/pkg/constant.BuildTime=$BUILD_TIME" -o ppanel-server ./ppanel.go
          tar -czf ppanel-server-${VERSION}-linux-amd64.tar.gz ppanel-server
          sha256sum ppanel-server ppanel-server-${VERSION}-linux-amd64.tar.gz > checksum.txt

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ppanel-server-linux-amd64
          path: |
            ppanel-server
            ppanel-server-*-linux-amd64.tar.gz
            checksum.txt

      - name: Create Release
        if: startsWith(github.ref, 'refs/tags/')
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          VERSION=${GITHUB_REF#refs/tags/}

          # Check if release exists
          if gh release view $VERSION >/dev/null 2>&1; then
            echo "Release $VERSION already exists, deleting old assets..."
            # Delete existing assets if they exist
            gh release delete-asset $VERSION ppanel-server-${VERSION}-linux-amd64.tar.gz --yes 2>/dev/null || true
            gh release delete-asset $VERSION checksum.txt --yes 2>/dev/null || true
          else
            echo "Creating new release $VERSION..."
            gh release create $VERSION --title "PPanel Server $VERSION" --notes "Release $VERSION"
          fi

          # Upload assets (will overwrite if --clobber is supported, otherwise will fail gracefully)
          echo "Uploading assets..."
          gh release upload $VERSION ppanel-server-${VERSION}-linux-amd64.tar.gz checksum.txt --clobber
