name: Build apt-ostree Package

# ⚠️  IMPORTANT: Each repository needs its own FORGEJO_TOKEN secret!
# 
# To set up this workflow in a new repository:
# 1. Go to repository settings: https://git.raines.xyz/OWNER/REPO/settings
# 2. Find "Secrets" or "Repository secrets" section
# 3. Add new secret:
#    - Name: FORGEJO_TOKEN
#    - Value: Your Personal Access Token with repo and write:packages permissions
# 4. The token needs these scopes:
#    - repo (Full control of private repositories)
#    - write:packages (Write packages)
#    - read:packages (Read packages)
#
# This workflow will fail with "FORGEJO_TOKEN is not set" if the secret is missing.

on:
  push:
    branches: [ main, master ]
  pull_request:
    branches: [ main, master ]
  workflow_dispatch:

env:
  UBUNTU_VERSION: "24.04"
  APT_OSTREE_VERSION: "0.1.0"

jobs:
  build-apt-ostree:
    name: Build apt-ostree Package
    runs-on: ubuntu-latest
    container:
      image: ubuntu:latest
    steps:
      - name: Setup build environment
        shell: bash
        run: |
          apt update -y
          apt install -y git curl pkg-config build-essential gnupg
          
          # Install system Rust packages first for dpkg-buildpackage compatibility
          apt install -y rustc cargo
          
          # Install Rust using rustup to get the latest version
          curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
          . ~/.cargo/env
          
          # Set default toolchain for rustup
          rustup default stable
          
          # Verify Rust version
          rustc --version
          cargo --version
          
          # Add Forgejo repository for libostree packages
          echo "Adding Forgejo repository for libostree packages..."
          curl -fsSL https://git.raines.xyz/api/packages/robojerk/debian/repository.key | gpg --dearmor -o /usr/share/keyrings/forgejo-robojerk.gpg
          echo "deb [signed-by=/usr/share/keyrings/forgejo-robojerk.gpg] https://git.raines.xyz/api/packages/robojerk/debian noble main" | tee /etc/apt/sources.list.d/forgejo-robojerk.list
          
          # Update package lists and install libostree packages
          apt update -y
          echo "Installing libostree packages from Forgejo repository..."
          apt install -y libostree-dev=2025.2-1~noble1 libostree-1-1=2025.2-1~noble1
          
          echo "✅ libostree packages installed successfully"
          echo "libostree-dev version: $(dpkg-query -W -f='${Version}' libostree-dev)"
          echo "libostree-1-1 version: $(dpkg-query -W -f='${Version}' libostree-1-1)"

      - name: Checkout repository manually
        run: |
          # Clone the repository manually instead of using actions/checkout
          git clone https://git.raines.xyz/robojerk/apt-ostree.git /tmp/apt-ostree
          cp -r /tmp/apt-ostree/* .
          cp -r /tmp/apt-ostree/.* . 2>/dev/null || true

      - name: Install curl and jq for API testing
        run: |
          apt-get update -y
          apt-get install -y curl jq

      - name: Debug - Check ACCESS_TOKEN (safe)
        run: |
          echo "=== Debugging ACCESS_TOKEN ==="
          echo "Token exists: ${{ secrets.ACCESS_TOKEN != '' }}"
          echo "Token length: ${#ACCESS_TOKEN}"
          echo "Token first 4 chars: $(echo "$ACCESS_TOKEN" | cut -c1-4)..."
          echo "Token last 4 chars: ...$(echo "$ACCESS_TOKEN" | rev | cut -c1-4 | rev)"
          echo "Environment variable name: ACCESS_TOKEN"
          echo "Available secrets:"
          env | grep -i token || echo "No token env vars found"
        env:
          ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}

      - name: Test API endpoints
        run: |
          echo "=== Testing Forgejo API endpoints with ACCESS_TOKEN ==="
          
          # Test 1: Check Forgejo version and capabilities
          echo "Testing Forgejo version..."
          curl -s -H "Authorization: Bearer ${{ secrets.ACCESS_TOKEN }}" \
               "https://git.raines.xyz/api/v1/version" | jq . 2>/dev/null || echo "Version endpoint failed"
          
          echo ""
          echo "=== Testing user info ==="
          
          # Test 2: Check user info
          echo "Testing user info..."
          curl -s -H "Authorization: Bearer ${{ secrets.ACCESS_TOKEN }}" \
               "https://git.raines.xyz/api/v1/user" | jq . 2>/dev/null || echo "User endpoint failed"
          
          echo ""
          echo "=== Testing repository info ==="
          
          # Test 3: Check repository info
          echo "Testing repository info..."
          curl -s -H "Authorization: Bearer ${{ secrets.ACCESS_TOKEN }}" \
               "https://git.raines.xyz/api/v1/repos/robojerk/apt-ostree" | jq . 2>/dev/null || echo "Repository endpoint failed"
          
          echo ""
          echo "=== Testing package registry endpoints ==="
          
          # Test 4: Check if package registry is enabled
          echo "Testing package registry availability..."
          curl -s -H "Authorization: Bearer ${{ secrets.ACCESS_TOKEN }}" \
               "https://git.raines.xyz/api/v1/user/packages" | jq . 2>/dev/null || echo "User packages endpoint failed"
          
          echo ""
          echo "=== Testing repository packages ==="
          
          # Test 5: Check repository packages
          echo "Testing repository packages..."
          curl -s -H "Authorization: Bearer ${{ secrets.ACCESS_TOKEN }}" \
               "https://git.raines.xyz/api/v1/repos/robojerk/apt-ostree/packages" | jq . 2>/dev/null || echo "Repository packages endpoint failed"
          
          echo ""
          echo "=== Testing Debian package registry ==="
          
          # Test 6: Check available package types
          echo "Testing Debian package registry..."
          curl -s -H "Authorization: Bearer ${{ secrets.ACCESS_TOKEN }}" \
               "https://git.raines.xyz/api/v1/packages/robojerk/debian" | jq . 2>/dev/null || echo "Debian packages endpoint failed"

      - name: Install additional build dependencies
        run: |
          apt update -y
          apt install -y debhelper-compat dh-cargo \
                         libglib2.0-dev libcurl4-gnutls-dev libssl-dev \
                         libsystemd-dev libmount-dev libselinux1-dev

      - name: Debug - List files before building
        run: |
          echo "Current directory: $(pwd)"
          echo "Files in current directory:"
          ls -la
          echo "Files in debian/ (if it exists):"
          ls -la debian/ 2>/dev/null || echo "debian/ directory does not exist"
          echo "Files in src/ (if it exists):"
          ls -la src/ 2>/dev/null || echo "src/ directory does not exist"

      - name: Build apt-ostree package
        shell: bash
        run: |
          echo "Building apt-ostree package..."
          # Source Rust environment and ensure default toolchain is set
          . ~/.cargo/env
          rustup default stable
          # Set environment variables for the entire build process
          export PATH="$HOME/.cargo/bin:$PATH"
          export CARGO_HOME="$HOME/.cargo"
          export RUSTUP_HOME="$HOME/.rustup"
          
          # Use the build script from debian directory
          if [ -f "debian/build.sh" ]; then
            echo "Using debian/build.sh..."
            chmod +x debian/build.sh
            ./debian/build.sh
          else
            echo "Using dpkg-buildpackage directly..."
            dpkg-buildpackage -us -uc -b
          fi

      - name: List built packages
        run: |
          echo "Built apt-ostree packages:"
          ls -la *.deb 2>/dev/null || echo "No .deb files found in current directory"
          ls -la ../*.deb 2>/dev/null || echo "No .deb files found in parent directory"
          
          # Also check for cargo build artifacts
          echo "Cargo build artifacts:"
          ls -la debian/cargo/target/release/ 2>/dev/null || echo "No cargo build artifacts found"
          
          # Check if apt-ostree binary was created
          if [ -f "debian/cargo/target/release/apt-ostree" ]; then
            echo "✅ apt-ostree binary found in cargo build"
            ./debian/cargo/target/release/apt-ostree --version || echo "⚠️ Version command failed"
          else
            echo "❌ apt-ostree binary not found in cargo build"
          fi

      - name: Upload to Debian Package Registry
        id: debian_upload
        shell: bash
        run: |
          echo "=== Attempting Debian Package Registry upload with ACCESS_TOKEN ==="
          
          # Check if ACCESS_TOKEN is available
          if [ -z "${{ secrets.ACCESS_TOKEN }}" ]; then
            echo "❌ ACCESS_TOKEN is not set"
            exit 1
          fi
          echo "✅ ACCESS_TOKEN is set"

          # Find .deb files in current and parent directories
          deb_files=$(find . -maxdepth 1 -name "*.deb" 2>/dev/null || true)
          deb_files="$deb_files $(find .. -maxdepth 1 -name "*.deb" 2>/dev/null || true)"
          
          if [ -z "$deb_files" ]; then
            echo "❌ No .deb files found to upload"
            exit 1
          fi

          for deb_file in $deb_files; do
            if [ -f "$deb_file" ]; then
              echo "Uploading $deb_file to Debian Package Registry..."
              filename=$(basename "$deb_file")
              echo "File: $filename"
              
              # Get HTTP code directly using curl -w
              http_code=$(curl -s -o /dev/null -w "%{http_code}" \
                               --user "robojerk:${{ secrets.ACCESS_TOKEN }}" \
                               --upload-file "$deb_file" \
                               "https://git.raines.xyz/api/packages/robojerk/debian/pool/noble/main/upload")
              
              echo "HTTP Response Code: $http_code"
              
              if [ "$http_code" = "201" ]; then
                echo "✅ Debian Package Registry upload SUCCESS for $deb_file"
              elif [ "$http_code" = "409" ]; then
                echo "➡️ INFO: Package $deb_file already exists (HTTP 409 Conflict)"
              else
                echo "❌ Debian Package Registry upload FAILED for $deb_file (HTTP $http_code)"
                # Show verbose output for debugging failures
                curl -v -i --user "robojerk:${{ secrets.ACCESS_TOKEN }}" \
                     --upload-file "$deb_file" \
                     "https://git.raines.xyz/api/packages/robojerk/debian/pool/noble/main/upload" 2>&1
                exit 1
              fi
            fi
          done

      - name: Create release assets
        run: |
          mkdir -p release-assets
          
          # Copy .deb files from current and parent directories
          cp *.deb release-assets/ 2>/dev/null || echo "No .deb files in current directory"
          cp ../*.deb release-assets/ 2>/dev/null || echo "No .deb files in parent directory"
          
          # Create a summary file
          echo "apt-ostree Package Build Summary" > release-assets/BUILD_SUMMARY.txt
          echo "=================================" >> release-assets/BUILD_SUMMARY.txt
          echo "Build Date: $(date)" >> release-assets/BUILD_SUMMARY.txt
          echo "Ubuntu Version: ${UBUNTU_VERSION}" >> release-assets/BUILD_SUMMARY.txt
          echo "apt-ostree Version: ${APT_OSTREE_VERSION}" >> release-assets/BUILD_SUMMARY.txt
          echo "" >> release-assets/BUILD_SUMMARY.txt
          echo "Built Packages:" >> release-assets/BUILD_SUMMARY.txt
          ls -la release-assets/*.deb 2>/dev/null || echo "No packages found" >> release-assets/BUILD_SUMMARY.txt
          
          # Create package list for download links
          echo "Package List:" > release-assets/PACKAGES.txt
          ls -1 release-assets/*.deb 2>/dev/null | sed 's|.*/||' >> release-assets/PACKAGES.txt
          
          echo "Release assets created:"
          ls -la release-assets/

      - name: Create download instructions
        run: |
          cat > release-assets/INSTALL.md << EOF
          # apt-ostree ${APT_OSTREE_VERSION} Installation
          
          ## Quick Install
          
          \`\`\`bash
          # Download and install the package
          wget https://git.raines.xyz/robojerk/apt-ostree/actions/runs/\${{ github.run_id }}/artifacts
          sudo dpkg -i apt-ostree_${APT_OSTREE_VERSION}-1_amd64.deb
          sudo apt-get install -f
          \`\`\`
          
          ## Verification
          
          \`\`\`bash
          # Check if apt-ostree is installed
          apt-ostree --version
          # Should output: apt-ostree ${APT_OSTREE_VERSION}
          \`\`\`
          
          ## Packages Included
          
          EOF
          
          ls -1 release-assets/*.deb 2>/dev/null | sed 's|.*/||' | while read package; do
            echo "- \`$package\`" >> release-assets/INSTALL.md
          done
          
          echo "" >> release-assets/INSTALL.md
          echo "Build completed on: $(date)" >> release-assets/INSTALL.md

      - name: Success Summary
        run: |
          echo "=== Upload Summary ==="
          echo "✅ All apt-ostree packages uploaded successfully to Forgejo Debian Package Registry"
          echo "✅ Packages automatically assigned to repository by Forgejo"
          echo ""
          echo "📦 Packages should now be available at:"
          echo "   https://git.raines.xyz/robojerk/apt-ostree/packages"
          echo ""
          echo "🎯 Next steps:"
          echo "   - Verify packages appear in repository packages page"
          echo "   - Test package installation on Ubuntu Noble systems"
          echo "   - Update ParticleOS installer to use packaged apt-ostree" 