name: DMS Stable Release to Copr

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      version:
        description: 'Versioning (e.g., 0.1.14, leave empty for latest release)'
        required: false
        default: ''

jobs:
  build-and-upload:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
      
      - name: Determine version
        id: version
        run: |
          if [ -n "${{ github.event.inputs.version }}" ]; then
            VERSION="${{ github.event.inputs.version }}"
            echo "Using manual version: $VERSION"
          elif [ "${{ github.event_name }}" = "release" ]; then
            VERSION="${{ github.event.release.tag_name }}"
            VERSION="${VERSION#v}"
            echo "Using release version: $VERSION"
          else
            # Fallback to latest release
            VERSION=$(curl -s https://api.github.com/repos/AvengeMedia/DankMaterialShell/releases/latest | jq -r '.tag_name' | sed 's/^v//')
            echo "Using latest release version: $VERSION"
          fi
          
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "✅ Building DMS stable version: $VERSION"
      
      - name: Setup build environment
        run: |
          sudo apt-get update
          sudo apt-get install -y rpm wget curl jq gzip
          mkdir -p ~/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
          echo "✅ RPM build environment ready"
      
      - name: Download release assets
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          cd ~/rpmbuild/SOURCES
          
          echo "📦 Downloading DMS release assets for v${VERSION}..."
          
          # Download DMS QML source
          wget "https://github.com/AvengeMedia/DankMaterialShell/releases/download/v${VERSION}/dms-qml.tar.gz" || {
            echo "❌ Failed to download dms-qml.tar.gz for v${VERSION}"
            exit 1
          }
          
          # Download dms-cli (always use latest)
          echo "📦 Downloading latest dms-cli..."
          wget "https://github.com/AvengeMedia/danklinux/releases/latest/download/dms-distropkg-amd64.gz" || {
            echo "❌ Failed to download dms-cli"
            exit 1
          }
          
          # Download dgop (always use latest)
          echo "📦 Downloading latest dgop..."
          wget "https://github.com/AvengeMedia/dgop/releases/latest/download/dgop-linux-amd64.gz" || {
            echo "❌ Failed to download dgop"
            exit 1
          }
          
          echo "✅ All sources downloaded"
          ls -lh
      
      - name: Generate stable spec file
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          CHANGELOG_DATE="$(date '+%a %b %d %Y')"

          cat > ~/rpmbuild/SPECS/dms.spec <<'SPECEOF'
          # Spec for DMS stable releases - Generated by GitHub Actions

          %global debug_package %{nil}
          %global version VERSION_PLACEHOLDER
          %global pkg_summary DankMaterialShell - Material 3 inspired shell for Wayland compositors

          Name:           dms
          Version:        %{version}
          Release:        1%{?dist}
          Summary:        %{pkg_summary}

          License:        GPL-3.0-only
          URL:            https://github.com/AvengeMedia/DankMaterialShell

          Source0:        dms-qml.tar.gz
          Source1:        dms-distropkg-amd64.gz
          Source2:        dgop-linux-amd64.gz

          BuildRequires:  gzip

          Requires:       (quickshell or quickshell-git)
          Requires:       dms-cli
          Requires:       dgop
          Requires:       fira-code-fonts
          Requires:       material-symbols-fonts
          Requires:       rsms-inter-fonts

          Recommends:     brightnessctl
          Recommends:     cava
          Recommends:     cliphist
          Recommends:     hyprpicker
          Recommends:     matugen
          Recommends:     wl-clipboard
          Recommends:     gammastep
          Recommends:     NetworkManager
          Suggests:       qt6ct

          %description
          DankMaterialShell (DMS) is a modern Wayland desktop shell built with Quickshell
          and optimized for the niri and hyprland compositors. Features notifications,
          app launcher, wallpaper customization, and fully customizable with plugins.

          Includes auto-theming for GTK/Qt apps with matugen, 20+ customizable widgets,
          process monitoring, notification center, clipboard history, dock, control center,
          lock screen, and comprehensive plugin system.

          %package -n dms-cli
          Summary:        DankMaterialShell CLI tool
          License:        GPL-3.0-only
          URL:            https://github.com/AvengeMedia/danklinux

          %description -n dms-cli
          Command-line interface for DankMaterialShell configuration and management.
          Provides native DBus bindings, NetworkManager integration, and system utilities.

          %package -n dgop
          Summary:        Stateless CPU/GPU monitor for DankMaterialShell
          License:        MIT
          URL:            https://github.com/AvengeMedia/dgop
          Provides:       dgop

          %description -n dgop
          DGOP is a stateless system monitoring tool that provides CPU, GPU, memory, and
          network statistics. Designed for integration with DankMaterialShell but can be
          used standalone. This package always includes the latest stable dgop release.

          %prep
          %setup -q -c -n dms-qml

          gunzip -c %{SOURCE1} > %{_builddir}/dms-cli
          chmod +x %{_builddir}/dms-cli

          gunzip -c %{SOURCE2} > %{_builddir}/dgop
          chmod +x %{_builddir}/dgop

          %build

          %install
          install -Dm755 %{_builddir}/dms-cli %{buildroot}%{_bindir}/dms
          install -Dm755 %{_builddir}/dgop %{buildroot}%{_bindir}/dgop

          install -dm755 %{buildroot}%{_sysconfdir}/xdg/quickshell/dms
          cp -r %{_builddir}/dms-qml/* %{buildroot}%{_sysconfdir}/xdg/quickshell/dms/

          rm -rf %{buildroot}%{_sysconfdir}/xdg/quickshell/dms/.git*
          rm -f %{buildroot}%{_sysconfdir}/xdg/quickshell/dms/.gitignore
          rm -rf %{buildroot}%{_sysconfdir}/xdg/quickshell/dms/.github
          rm -f %{buildroot}%{_sysconfdir}/xdg/quickshell/dms/*.spec

          %files
          %license LICENSE
          %doc README.md CONTRIBUTING.md
          %{_sysconfdir}/xdg/quickshell/dms/

          %files -n dms-cli
          %{_bindir}/dms

          %files -n dgop
          %{_bindir}/dgop

          %changelog
          * CHANGELOG_DATE_PLACEHOLDER AvengeMedia <contact@avengemedia.com> - VERSION_PLACEHOLDER-1
          - Stable release VERSION_PLACEHOLDER
          - Built from GitHub release
          - Includes latest dms-cli and dgop binaries
          SPECEOF

          sed -i "s/VERSION_PLACEHOLDER/${VERSION}/g" ~/rpmbuild/SPECS/dms.spec
          sed -i "s/CHANGELOG_DATE_PLACEHOLDER/${CHANGELOG_DATE}/g" ~/rpmbuild/SPECS/dms.spec
          
          echo "✅ Spec file generated for v${VERSION}"
          echo ""
          echo "=== Spec file preview ==="
          head -40 ~/rpmbuild/SPECS/dms.spec
      
      - name: Build SRPM
        id: build
        run: |
          cd ~/rpmbuild/SPECS
          
          echo "🔨 Building SRPM..."
          rpmbuild -bs dms.spec
          
          SRPM=$(ls ~/rpmbuild/SRPMS/*.src.rpm | tail -n 1)
          SRPM_NAME=$(basename "$SRPM")
          
          echo "srpm_path=$SRPM" >> $GITHUB_OUTPUT
          echo "srpm_name=$SRPM_NAME" >> $GITHUB_OUTPUT
          
          echo "✅ SRPM built: $SRPM_NAME"
          echo ""
          echo "=== SRPM Info ==="
          rpm -qpi "$SRPM"
      
      - name: Upload SRPM artifact
        uses: actions/upload-artifact@v4
        with:
          name: dms-stable-srpm-${{ steps.version.outputs.version }}
          path: ${{ steps.build.outputs.srpm_path }}
          retention-days: 90
      
      - name: Install Copr CLI
        run: |
          sudo apt-get install -y python3-pip
          pip3 install copr-cli
          
          mkdir -p ~/.config
          cat > ~/.config/copr << EOF
          [copr-cli]
          login = ${{ secrets.COPR_LOGIN }}
          username = avengemedia
          token = ${{ secrets.COPR_TOKEN }}
          copr_url = https://copr.fedorainfracloud.org
          EOF
          chmod 600 ~/.config/copr
          
          echo "✅ Copr CLI configured"
      
      - name: Upload to Copr
        run: |
          SRPM="${{ steps.build.outputs.srpm_path }}"
          VERSION="${{ steps.version.outputs.version }}"
          
          echo "🚀 Uploading SRPM to avengemedia/dms..."
          echo "   SRPM: $(basename $SRPM)"
          echo "   Version: $VERSION"
          
          BUILD_OUTPUT=$(copr-cli build avengemedia/dms "$SRPM" --nowait 2>&1)
          echo "$BUILD_OUTPUT"
          
          BUILD_ID=$(echo "$BUILD_OUTPUT" | grep -oP 'Build was added to.*\K[0-9]+' || echo "unknown")
          
          if [ "$BUILD_ID" != "unknown" ]; then
            echo "✅ Build submitted successfully!"
            echo "🔗 https://copr.fedorainfracloud.org/coprs/avengemedia/dms/build/$BUILD_ID/"
          else
            echo "⚠️  Could not extract build ID, but upload may have succeeded"
          fi
      
      - name: Build summary
        if: always()
        run: |
          echo "### 🎉 DMS Stable Build Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- **Version:** ${{ steps.version.outputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "- **SRPM:** ${{ steps.build.outputs.srpm_name }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Project:** https://copr.fedorainfracloud.org/coprs/avengemedia/dms/" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Stable release has been built and uploaded to Copr!" >> $GITHUB_STEP_SUMMARY
