#!/bin/sh

REPO_CONF_NAME="pkg.conf"

cat > pkg.conf << EOF
    vbox_ose: {
        url: "file://${PWD}",
        enabled: yes,
        priority: 100
    }
EOF

pkg -o REPOS_DIR="$PWD" -o repositories_conf="$REPO_CONF_NAME" install -y virtualbox-ose-additions

RC_CONF="/etc/rc.conf"
LOADER_CONF="/boot/loader.conf"

echo "[*] Configuring VirtualBox guest modules..."

# rc.conf
grep -q '^vboxguest_enable=' "$RC_CONF" || echo 'vboxguest_enable="YES"' >> "$RC_CONF"
grep -q '^vboxservice_enable=' "$RC_CONF" || echo 'vboxservice_enable="YES"' >> "$RC_CONF"

echo "[+] rc.conf updated"

# loader.conf
grep -q '^vboxguest_load=' "$LOADER_CONF" || echo 'vboxguest_load="YES"' >> "$LOADER_CONF"
grep -q '^vboxservice_load=' "$LOADER_CONF" || echo 'vboxservice_load="YES"' >> "$LOADER_CONF"
grep -q '^vboxvideo_load=' "$LOADER_CONF" || echo 'vboxvideo_load="YES"' >> "$LOADER_CONF"

echo "[+] loader.conf updated"

# load now
kldload vboxguest 2>/dev/null
kldload vboxservice 2>/dev/null
kldload vboxvideo 2>/dev/null

echo "[+] Modules loaded (if available)"
echo "[✓] Done"
