name: Test Virgin User

on:
  workflow_call:

jobs:
  test-virgin-user:
    runs-on: ubuntu-latest
    timeout-minutes: 45
    strategy:
      fail-fast: false
      matrix:
        distro: [arch, debian, ubuntu, fedora, centos]

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

      - name: Show Docker version
        run: docker version

      # 🔹 BUILD virgin image if missing
      - name: Build virgin container (${{ matrix.distro }})
        run: |
          set -euo pipefail
          PKGMGR_DISTRO="${{ matrix.distro }}" make build-missing-virgin

      # 🔹 RUN test inside virgin image as non-root
      - name: Virgin ${{ matrix.distro }} pkgmgr test (user)
        run: |
          set -euo pipefail

          docker run --rm \
            -v "$PWD":/src \
            -w /src \
            "pkgmgr-${{ matrix.distro }}-virgin" \
            bash -lc '
              set -euo pipefail

              make install

              useradd -m dev
              echo "dev ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dev
              chmod 0440 /etc/sudoers.d/dev
              chown -R dev:dev /src

              mkdir -p /nix/store /nix/var/nix /nix/var/log/nix /nix/var/nix/profiles
              chown -R dev:dev /nix
              chmod 0755 /nix
              chmod 1777 /nix/store

              sudo -H -u dev env HOME=/home/dev PKGMGR_DISABLE_NIX_FLAKE_INSTALLER=1 bash -lc "
                set -euo pipefail
                cd /src

                make setup-venv
                . \"\$HOME/.venvs/pkgmgr/bin/activate\"

                pkgmgr version pkgmgr

                export NIX_REMOTE=local
                nix run /src#pkgmgr -- version pkgmgr
              "
            '
