#!/bin/sh
# 9000-bee-setup.hook.chroot — runs inside Debian chroot during live-build
# Enables bee systemd services and configures the live environment.
set -e

echo "=== bee chroot setup ==="

ensure_bee_console_user() {
    if id bee >/dev/null 2>&1; then
        usermod -d /home/bee -s /bin/sh bee 2>/dev/null || true
    else
        useradd -d /home/bee -m -s /bin/sh -U bee
    fi

    mkdir -p /home/bee
    chown -R bee:bee /home/bee
    echo "bee:eeb" | chpasswd
    usermod -aG sudo,video,input bee 2>/dev/null || true
}

ensure_bee_console_user

# Enable bee services
systemctl enable nvidia-dcgm.service 2>/dev/null || true
systemctl enable bee-network.service
systemctl enable bee-nvidia.service
systemctl enable bee-preflight.service
systemctl enable bee-audit.service
systemctl enable bee-web.service
systemctl enable bee-sshsetup.service
systemctl enable ssh.service
systemctl enable lightdm.service 2>/dev/null || true
systemctl enable qemu-guest-agent.service 2>/dev/null || true
systemctl enable serial-getty@ttyS0.service 2>/dev/null || true
systemctl enable serial-getty@ttyS1.service 2>/dev/null || true
systemctl enable bee-journal-mirror@ttyS1.service 2>/dev/null || true

# Ensure scripts are executable
chmod +x /usr/local/bin/bee-network.sh  2>/dev/null || true
chmod +x /usr/local/bin/bee-nvidia-load 2>/dev/null || true
chmod +x /usr/local/bin/bee-sshsetup   2>/dev/null || true
chmod +x /usr/local/bin/bee-smoketest  2>/dev/null || true
chmod +x /usr/local/bin/bee            2>/dev/null || true
chmod +x /usr/local/bin/bee-log-run    2>/dev/null || true

# Reload udev rules
udevadm control --reload-rules 2>/dev/null || true

# rocm-smi symlink (package installs to /opt/rocm-*/bin/rocm-smi)
if [ ! -e /usr/local/bin/rocm-smi ]; then
    smi_path="$(find /opt -path '*/bin/rocm-smi' -type f 2>/dev/null | sort | tail -1)"
    [ -n "${smi_path}" ] && ln -sf "${smi_path}" /usr/local/bin/rocm-smi
fi

# Create export directory
mkdir -p /appdata/bee/export

if [ -f /etc/sudoers.d/bee ]; then
    chmod 0440 /etc/sudoers.d/bee
fi

echo "=== bee chroot setup complete ==="
