name: Installer Build

on:
  push:
    branches: [ "main" ]
    paths:
      - ".github/workflows/installer_build.yml"
      - "src/main/csharp/net/eagle0/clients/win/installer/**"
  pull_request:
    paths:
      - ".github/workflows/installer_build.yml"
      - "src/main/csharp/net/eagle0/clients/win/installer/**"

permissions:
  contents: read

jobs:
  build-installer:
    runs-on: self-hosted

    steps:
      - uses: actions/checkout@v4
        with:
          lfs: false
          clean: false

      - name: Setup .NET 8
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '8.0.x'

      - name: Restore dependencies
        run: dotnet restore src/main/csharp/net/eagle0/clients/win/installer/EagleInstaller/EagleInstaller.csproj

      - name: Build installer
        run: dotnet publish src/main/csharp/net/eagle0/clients/win/installer/EagleInstaller/EagleInstaller.csproj -c Release -r win-x64 --self-contained true --output ./installer-output

      - name: Archive installer binary
        if: success() || failure()
        uses: actions/upload-artifact@v4
        with:
          name: eagle-installer
          path: ./installer-output/EagleInstaller.exe

      - name: Verify installer exists
        if: success()
        run: |
          if [ ! -f "./installer-output/EagleInstaller.exe" ]; then
            echo "ERROR: EagleInstaller.exe not found at expected location"
            echo "Directory contents:"
            ls -la ./installer-output/
            exit 1
          fi
          echo "Installer found at correct location"

      - name: Deploy installer
        if: success() && github.ref == 'refs/heads/main' && github.event_name == 'push'
        env:
          ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
          SECRET_KEY: ${{ secrets.SECRET_KEY }}
        run: |
          INSTALLER_PATH="$(pwd)/installer-output/EagleInstaller.exe"
          echo "Using absolute path: $INSTALLER_PATH"
          bazel run //src/main/go/net/eagle0/build/installer_build_handler:installer_build_handler -- "$INSTALLER_PATH"

      - name: Update unified manifest
        if: success() && github.ref == 'refs/heads/main' && github.event_name == 'push'
        env:
          ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
          SECRET_KEY: ${{ secrets.SECRET_KEY }}
        run: |
          # Create installer manifest content  
          INSTALLER_SHA=$(sha256sum ./installer-output/EagleInstaller.exe | cut -d' ' -f1)
          echo "installer_version=$INSTALLER_SHA" > /tmp/installer_manifest.txt
          echo "installer_url=installer/EagleInstaller.exe" >> /tmp/installer_manifest.txt
          
          echo "=== Installer manifest content ==="
          cat /tmp/installer_manifest.txt
          echo "=================================="
          
          # Update the unified manifest
          bazel run //src/main/go/net/eagle0/build/manifest_manager:manifest_manager -- installer /tmp/installer_manifest.txt