Vagrant.configure('2') do |config|
  # Default: $env:DEV = "false" ; $env:LOCATION = "remote"
  # DEV:     $env:DEV = "true"  ; $env:LOCATION = "local"  ; vagrant up

  dev_arg      = ENV.fetch('DEV', 'false').to_s
  location_arg = ENV.fetch('LOCATION', 'remote').to_s

  config.vm.boot_timeout = 600

  # ---------- Hyper-V ----------
  config.vm.define 'hyper-v_vm' do |hv_vm|
    hv_vm.vm.box      = 'generic/debian12'
    hv_vm.vm.hostname = 'WiFiChallengeLab'

    hv_vm.vm.provider 'hyperv' do |hv|
      hv.vmname    = 'WiFiChallenge Lab v2.4.1'
      hv.maxmemory = 4096
      hv.memory    = 4096
      hv.cpus      = 4
      # Note: Hyper-V does not typically expose a normal audio device to Linux guests.
    end

    hv_vm.vm.provision 'shell',
      inline: <<~SHELL,
        set -e
        apt-get update -y
        DEBIAN_FRONTEND=noninteractive apt-get full-upgrade -y
      SHELL
      privileged: true,
      run: 'once'

    hv_vm.vm.provision 'reload', name: 'Reboot after update kernel'

    hv_vm.vm.provision 'shell',
      path: './install.sh',
      args: [dev_arg, location_arg],
      privileged: true

    hv_vm.vm.provision 'reload', name: 'Reboot after update kernel'

    hv_vm.vm.provision 'shell',
      inline: <<~SHELL,
        for K in $(dpkg --list | awk '/linux-image-[0-9]/{print $2}' | grep -v $(uname -r)); do sudo apt remove --purge -y $K; done
        sudo dd if=/dev/zero of=/tmp/zerofile bs=1M || true
        sudo rm -f /tmp/zerofile
      SHELL
      privileged: true,
      run: 'once'
  end

  # ---------- VirtualBox ----------
  config.vm.define 'virtualbox_vm' do |vb_vm|
    vb_vm.vm.box      = 'generic/debian12'
    vb_vm.vm.hostname = 'WiFiChallengeLab'

    vb_vm.vm.provider 'virtualbox' do |vb|
      vb.memory = 4096
      vb.cpus   = 4
      vb.name   = 'WiFiChallenge Lab v2.4.1'
      vb.customize ['modifyvm', :id, '--graphicscontroller', 'vmsvga']
      vb.check_guest_additions = false
      vb.functional_vboxsf = false
      vb.customize ['modifyvm', :id, '--audiocontroller', 'hda']
      # If you ever need a fallback, swap controller to ac97:
      # vb.customize ['modifyvm', :id, '--audiocontroller', 'ac97']
    end

    host_ga_iso =
      if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
        'C:/Program Files/Oracle/VirtualBox/VBoxGuestAdditions.iso'
      elsif RUBY_PLATFORM =~ /darwin/
        '/Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso'
      else
        File.exist?('/usr/share/virtualbox/VBoxGuestAdditions.iso') ?
          '/usr/share/virtualbox/VBoxGuestAdditions.iso' :
          '/usr/lib/virtualbox/additions/VBoxGuestAdditions.iso'
      end

    vb_vm.vm.provision 'file',
      source: host_ga_iso,
      destination: '/tmp/VBoxGuestAdditions.iso',
      run: 'always'

    vb_vm.vm.provision 'shell',
      inline: <<~SHELL,
        set -e
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -y
        apt-get full-upgrade -y
      SHELL
      privileged: true,
      run: 'once'

    vb_vm.vm.provision 'reload', name: 'Reboot after kernel upgrade'

    vb_vm.vm.provision 'shell',
      inline: <<~'SHELL',
        set -e
        mkdir -p /mnt/vbga

        if [ ! -s /tmp/VBoxGuestAdditions.iso ]; then
          echo "Guest Additions ISO missing or empty at /tmp/VBoxGuestAdditions.iso"
          ls -l /tmp || true
          exit 1
        fi
        file /tmp/VBoxGuestAdditions.iso || true

        apt-get update -y
        apt-get install -y kmod util-linux
        modprobe loop || true
        modprobe isofs || true

        losetup -fP /tmp/VBoxGuestAdditions.iso
        LOOPDEV="$(losetup -j /tmp/VBoxGuestAdditions.iso | awk -F: '{print $1}')"
        if [ -z "$LOOPDEV" ]; then
          echo "Could not attach loop device"
          losetup -a || true
          exit 1
        fi

        mount -t iso9660 -o ro "$LOOPDEV" /mnt/vbga || {
          echo "Mount failed. Dumping loop devices"
          losetup -a || true
          exit 1
        }

        if [ ! -x /mnt/vbga/VBoxLinuxAdditions.run ]; then
          echo "VBoxLinuxAdditions.run not found on ISO"
          umount /mnt/vbga
          losetup -d "$LOOPDEV"
          exit 1
        fi

        sh /mnt/vbga/VBoxLinuxAdditions.run --nox11 || true

        umount /mnt/vbga || true
        losetup -d "$LOOPDEV" || true

        /sbin/rcvboxadd quicksetup all || true
        /sbin/rcvboxadd reload || true
      SHELL
      privileged: true

    vb_vm.vm.provision 'reload', name: 'Reboot after GA install'

    vb_vm.vm.provision 'shell',
      path: './install.sh',
      args: [dev_arg, location_arg],
      privileged: true

    vb_vm.vm.provision 'reload', name: 'Reboot after update kernel'

    vb_vm.vm.provision 'shell',
      inline: <<~SHELL,
        for K in $(dpkg --list | awk '/linux-image-[0-9]/{print $2}' | grep -v $(uname -r)); do sudo apt remove --purge -y $K; done
        sudo dd if=/dev/zero of=/tmp/zerofile bs=1M || true
        sudo rm -f /tmp/zerofile
      SHELL
      privileged: true,
      run: 'once'
  end

  # ---------- VMware ----------
  config.vm.define 'vmware_vm' do |vmw_vm|
    vmw_vm.vm.box      = 'generic/debian12'
    vmw_vm.vm.hostname = 'WiFiChallengeLab'

    vmw_vm.vm.provider 'vmware_desktop' do |v|
      v.linked_clone         = false
      v.clone_directory      = 'E:/VMWare'
      v.force_vmware_license = 'workstation'
      v.gui                  = true
      v.vmx['displayName']   = 'WiFiChallenge Lab v2.4.1'
      v.memory               = 4096
      v.cpus                 = 4
      # Force sound device present/connected (Windows host)
      v.vmx['sound.present']        = 'TRUE'
      v.vmx['sound.autodetect']     = 'TRUE'
      v.vmx['sound.startConnected'] = 'TRUE'
    end

    vmw_vm.vm.provision 'shell',
      inline: <<~SHELL,
        set -e
        apt-get update -y
        DEBIAN_FRONTEND=noninteractive apt-get full-upgrade -y
      SHELL
      privileged: true,
      run: 'once'

    vmw_vm.vm.provision 'reload', name: 'Reboot after update kernel'

    vmw_vm.vm.provision 'shell',
      path: './install.sh',
      args: [dev_arg, location_arg],
      privileged: true

    vmw_vm.vm.provision 'reload', name: 'Reboot after update kernel'

    vmw_vm.vm.provision 'shell',
      inline: <<~SHELL,
        for K in $(dpkg --list | awk '/linux-image-[0-9]/{print $2}' | grep -v $(uname -r)); do sudo apt remove --purge -y $K; done
        sudo dd if=/dev/zero of=/tmp/zerofile bs=1M || true
        sudo rm -f /tmp/zerofile
      SHELL
      privileged: true,
      run: 'once'
  end

  # ---------- QEMU ----------
  config.vm.define 'qemu_vm' do |qemu_vm|
    qemu_vm.vm.box      = 'generic/debian12'
    qemu_vm.vm.hostname = 'WiFiChallengeLab'

    qemu_vm.vm.provider 'qemu' do |qemu|
      qemu.memory            = 4096
      qemu.cpus              = 4
      qemu.machine           = 'q35'
      qemu.cpu               = 'host'
      qemu.video_type        = 'virtio'
      qemu.display           = 'gtk'
      qemu.audio             = 'on'
      qemu.disk_interface    = 'virtio'
      qemu.network_interface = 'virtio-net'
      qemu.name              = 'WiFiChallenge Lab v2.4.1 (QEMU)'
      qemu.qemu_dir          = 'C:/Program Files/qemu'
      qemu.uefi              = 'C:/Program Files/qemu/share/edk2-x86_64-code.fd'
      qemu.gui               = true
      qemu.extra_qemu_args = [
        '-audiodev', 'dsound,id=snd0',
        '-device', 'ich9-intel-hda',
        '-device', 'hda-duplex,audiodev=snd0'
      ]
    end

    qemu_vm.vm.provision 'shell',
      inline: <<~SHELL,
        set -e
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -y
        apt-get full-upgrade -y
      SHELL
      privileged: true,
      run: 'once'

    qemu_vm.vm.provision 'reload', name: 'Reboot after kernel upgrade'

    qemu_vm.vm.provision 'shell',
      inline: <<~SHELL,
        set -e
        apt-get install -y qemu-guest-agent spice-vdagent xserver-xorg-video-qxl
        systemctl enable qemu-guest-agent
        systemctl start qemu-guest-agent
      SHELL
      privileged: true

    qemu_vm.vm.provision 'reload', name: 'Reboot after guest tools install'

    qemu_vm.vm.provision 'shell',
      path: './install.sh',
      args: [dev_arg, location_arg],
      privileged: true

    qemu_vm.vm.provision 'reload', name: 'Reboot after update kernel'

    qemu_vm.vm.provision 'shell',
      inline: <<~SHELL,
        for K in $(dpkg --list | awk '/linux-image-[0-9]/{print $2}' | grep -v $(uname -r)); do sudo apt remove --purge -y $K; done
        sudo dd if=/dev/zero of=/tmp/zerofile bs=1M || true
        sudo rm -f /tmp/zerofile
      SHELL
      privileged: true,
      run: 'once'
  end
end
