name: Release APT Package

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      version:
        description: "Version to release (e.g., 0.69.20)"
        required: true

permissions:
  contents: write
  packages: write

jobs:
  build-deb:
    name: Build Debian Package
    runs-on: ubuntu-latest
    strategy:
      matrix:
        arch: [amd64, arm64]

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

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: "1.23"

      - name: Get version
        id: version
        run: |
          if [ "${{ github.event_name }}" = "release" ]; then
            VERSION="${{ github.event.release.tag_name }}"
            VERSION="${VERSION#v}"  # Remove 'v' prefix if present
          else
            VERSION="${{ github.event.inputs.version }}"
          fi
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Set up QEMU (for arm64)
        if: matrix.arch == 'arm64'
        uses: docker/setup-qemu-action@v3

      - name: Build binary
        env:
          GOARCH: ${{ matrix.arch }}
          CGO_ENABLED: 0
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          COMMIT=$(git rev-parse --short HEAD)
          DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)
          LDFLAGS="-X 'main.version=$VERSION' -X 'main.commit=$COMMIT' -X 'main.date=$DATE'"

          mkdir -p build/usr/local/bin
          go build -ldflags "$LDFLAGS" -o build/usr/local/bin/orama cmd/cli/main.go
          go build -ldflags "$LDFLAGS" -o build/usr/local/bin/debros-node cmd/node/main.go
          # Build the entire gateway package so helper files (e.g., config parsing) are included
          go build -ldflags "$LDFLAGS" -o build/usr/local/bin/debros-gateway ./cmd/gateway

      - name: Create Debian package structure
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          ARCH="${{ matrix.arch }}"
          PKG_NAME="orama_${VERSION}_${ARCH}"

          mkdir -p ${PKG_NAME}/DEBIAN
          mkdir -p ${PKG_NAME}/usr/local/bin

          # Copy binaries
          cp build/usr/local/bin/* ${PKG_NAME}/usr/local/bin/
          chmod 755 ${PKG_NAME}/usr/local/bin/*

          # Create control file
          cat > ${PKG_NAME}/DEBIAN/control << EOF
          Package: orama
          Version: ${VERSION}
          Section: net
          Priority: optional
          Architecture: ${ARCH}
          Depends: libc6
          Maintainer: DeBros Team <team@orama.network>
          Description: Orama Network - Distributed P2P Database System
           Orama is a distributed peer-to-peer network that combines
           RQLite for distributed SQL, IPFS for content-addressed storage,
           and LibP2P for peer discovery and communication.
          EOF

          # Create postinst script
          cat > ${PKG_NAME}/DEBIAN/postinst << 'EOF'
          #!/bin/bash
          set -e
          echo ""
          echo "Orama installed successfully!"
          echo ""
          echo "To set up your node, run:"
          echo "  sudo orama install"
          echo ""
          EOF
          chmod 755 ${PKG_NAME}/DEBIAN/postinst

      - name: Build .deb package
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          ARCH="${{ matrix.arch }}"
          PKG_NAME="orama_${VERSION}_${ARCH}"

          dpkg-deb --build ${PKG_NAME}
          mv ${PKG_NAME}.deb orama_${VERSION}_${ARCH}.deb

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: deb-${{ matrix.arch }}
          path: "*.deb"

  publish-apt:
    name: Publish to APT Repository
    needs: build-deb
    runs-on: ubuntu-latest

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

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: packages

      - name: Get version
        id: version
        run: |
          if [ "${{ github.event_name }}" = "release" ]; then
            VERSION="${{ github.event.release.tag_name }}"
            VERSION="${VERSION#v}"
          else
            VERSION="${{ github.event.inputs.version }}"
          fi
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Set up GPG
        if: env.GPG_PRIVATE_KEY != ''
        env:
          GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
        run: |
          echo "$GPG_PRIVATE_KEY" | gpg --import

      - name: Create APT repository structure
        run: |
          mkdir -p apt-repo/pool/main/o/orama
          mkdir -p apt-repo/dists/stable/main/binary-amd64
          mkdir -p apt-repo/dists/stable/main/binary-arm64

          # Move packages
          mv packages/deb-amd64/*.deb apt-repo/pool/main/o/orama/
          mv packages/deb-arm64/*.deb apt-repo/pool/main/o/orama/

          # Generate Packages files
          cd apt-repo
          dpkg-scanpackages --arch amd64 pool/ > dists/stable/main/binary-amd64/Packages
          dpkg-scanpackages --arch arm64 pool/ > dists/stable/main/binary-arm64/Packages

          gzip -k dists/stable/main/binary-amd64/Packages
          gzip -k dists/stable/main/binary-arm64/Packages

          # Generate Release file
          cat > dists/stable/Release << EOF
          Origin: Orama
          Label: Orama
          Suite: stable
          Codename: stable
          Architectures: amd64 arm64
          Components: main
          Description: Orama Network APT Repository
          EOF

          cd ..

      - name: Upload to release
        if: github.event_name == 'release'
        uses: softprops/action-gh-release@v1
        with:
          files: |
            apt-repo/pool/main/o/orama/*.deb
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Deploy APT repository to GitHub Pages
        uses: peaceiris/actions-gh-pages@v4
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./apt-repo
          destination_dir: apt
          keep_files: true
