name: Release to Ubuntu PPA

on:
  workflow_dispatch:
    inputs:
      ubuntu_release:
        description: 'Ubuntu release codename'
        required: true
        default: 'oracular'
        type: choice
        options:
          - oracular # 24.10 with Rust 1.81
          - noble # 24.04 LTS with Rust 1.82
      tarball_suffix:
        description: 'Tarball suffix (e.g., ds1, ds2) - leave empty for new releases'
        required: false
        default: ''
        type: string
  push:
    tags:
      - 'v*'

env:
  DEBEMAIL: cadetg@gmail.com
  DEBFULLNAME: Marco Cadetg
  PPA: ppa:domcyrus/rustnet

jobs:
  build-and-upload:
    runs-on: ubuntu-24.04
    strategy:
      matrix:
        ubuntu_release:
          - questing

    steps:
      - name: Checkout code
        uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y \
            debhelper \
            devscripts \
            dput \
            gnupg \
            libpcap-dev \
            libelf-dev \
            elfutils \
            zlib1g-dev \
            clang \
            llvm \
            pkg-config

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: stable

      - name: Import GPG key
        env:
          GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
        run: |
          echo "$GPG_PRIVATE_KEY" | gpg --batch --import
          gpg --list-secret-keys

      - name: Get version
        id: version
        run: |
          VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')

          # Add tarball suffix if provided (e.g., +ds1, +ds2)
          TARBALL_SUFFIX="${{ github.event.inputs.tarball_suffix }}"
          if [ -n "$TARBALL_SUFFIX" ]; then
            TARBALL_VERSION="${VERSION}+${TARBALL_SUFFIX}"
            echo "version=$TARBALL_VERSION" >> $GITHUB_OUTPUT
            echo "Using tarball version: $TARBALL_VERSION"
          else
            echo "version=$VERSION" >> $GITHUB_OUTPUT
            echo "Using version: $VERSION"
          fi

          # Extract Debian revision from changelog
          DEBIAN_REVISION=$(head -1 debian/changelog | sed 's/.*(\(.*\)-\(.*\)).*/\2/')
          echo "debian_revision=$DEBIAN_REVISION" >> $GITHUB_OUTPUT

      - name: Update changelog
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          CURRENT_VERSION=$(head -1 debian/changelog | sed 's/.*(\(.*\)).*/\1/')

          if [ "$VERSION-1ubuntu1" != "$CURRENT_VERSION" ]; then
            echo "Updating changelog from $CURRENT_VERSION to $VERSION-1ubuntu1"

            # Create new changelog entry
            DEBFULLNAME="${{ env.DEBFULLNAME }}" DEBEMAIL="${{ env.DEBEMAIL }}" \
              dch --newversion "$VERSION-1ubuntu1" \
                  --distribution "questing" \
                  "New upstream release $VERSION"

            echo "✓ Changelog updated"
          else
            echo "✓ Changelog already at correct version"
          fi

      - name: Build source package
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          BASE_VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
          PACKAGE_NAME="rustnet-monitor"

          # Create build directory
          mkdir -p build-ppa

          # Extract source from release tag
          RELEASE_TAG="v${BASE_VERSION}"
          if git rev-parse "$RELEASE_TAG" >/dev/null 2>&1; then
            echo "✓ Found release tag: $RELEASE_TAG"
            git archive --format=tar --prefix="${PACKAGE_NAME}-${VERSION}/" "$RELEASE_TAG" | tar -x -C build-ppa
          else
            echo "⚠ Release tag $RELEASE_TAG not found, using HEAD"
            git archive --format=tar --prefix="${PACKAGE_NAME}-${VERSION}/" HEAD | tar -x -C build-ppa
          fi

          # Vendor dependencies separately from orig tarball
          echo "Vendoring Rust dependencies..."
          cd build-ppa/${PACKAGE_NAME}-${VERSION}

          cargo vendor vendor

          # Remove prebuilt static libraries (keep .dll for tests)
          echo "Cleaning vendor directory..."
          find vendor -name "*.a" -delete
          find vendor -name "*.lib" -delete

          # Pack vendor directory as separate tarball in debian/
          echo "Creating vendor tarball..."
          tar -cJf ../vendor.tar.xz vendor
          rm -rf vendor

          # Create orig tarball (without vendor directory)
          echo "Creating orig tarball..."
          cd ..
          ORIG_TARBALL="${PACKAGE_NAME}_${VERSION}.orig.tar.gz"
          tar -czf "${ORIG_TARBALL}" "${PACKAGE_NAME}-${VERSION}"

          # Add debian directory and vendor tarball
          cp -r "$GITHUB_WORKSPACE/debian" "${PACKAGE_NAME}-${VERSION}/"
          mv vendor.tar.xz "${PACKAGE_NAME}-${VERSION}/debian/"

          # Build source package
          cd "${PACKAGE_NAME}-${VERSION}"

          # Always use -sa to include orig tarball
          # Launchpad will reuse existing file if hash matches
          debuild -S -sa -d -us -uc

      - name: Sign and upload
        env:
          GPG_KEY_ID: ${{ secrets.GPG_KEY_ID }}
        run: |
          cd build-ppa
          VERSION="${{ steps.version.outputs.version }}"
          DEBIAN_REVISION="${{ steps.version.outputs.debian_revision }}"
          CHANGES_FILE="rustnet-monitor_${VERSION}-${DEBIAN_REVISION}_source.changes"

          # Sign
          debsign -k${GPG_KEY_ID} ${CHANGES_FILE}

          # Verify
          gpg --verify ${CHANGES_FILE}

          # Upload to PPA
          dput ${{ env.PPA }} ${CHANGES_FILE}

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ppa-source-${{ matrix.ubuntu_release }}
          path: |
            build-ppa/*.dsc
            build-ppa/*.tar.gz
            build-ppa/*.tar.xz
            build-ppa/*.changes
            build-ppa/*.buildinfo
          retention-days: 30

      - name: Summary
        run: |
          echo "## 🎉 PPA Upload Complete" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- **Package**: rustnet-monitor" >> $GITHUB_STEP_SUMMARY
          echo "- **Version**: ${{ steps.version.outputs.version }}-${{ steps.version.outputs.debian_revision }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Ubuntu**: ${{ matrix.ubuntu_release }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### Installation" >> $GITHUB_STEP_SUMMARY
          echo '```bash' >> $GITHUB_STEP_SUMMARY
          echo "sudo add-apt-repository ppa:domcyrus/rustnet" >> $GITHUB_STEP_SUMMARY
          echo "sudo apt update && sudo apt install rustnet" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "[View PPA →](https://launchpad.net/~domcyrus/+archive/ubuntu/rustnet/+packages)" >> $GITHUB_STEP_SUMMARY
