#! /bin/sh
# shellcheck disable=SC3043

PREFIX=/usr/local
LOCALBASE=/usr/local
VERSION=0.5.0
SCRIPT=${PREFIX}/sbin/wifibox
LOGDIR=/var/log/wifibox
RUNDIR=/var/run/wifibox
CONFDIR=${PREFIX}/etc/wifibox
BHYVE_LOG=${LOGDIR}/bhyve.log
GRUB_BHYVE_LOG=${LOGDIR}/grub-bhyve.log

: "${BHYVE:=/usr/local/sbin/bhyve}"
: "${BHYVECTL:=/usr/local/sbin/bhyvectl}"
: "${VMM_KO:=/boot/modules/vmm.ko}"
: "${DEVCTL:=/usr/sbin/devctl}"
: "${IFCONFIG:=/sbin/ifconfig}"
: "${SYSCTL:=/sbin/sysctl}"
: "${KLDLOAD:=/sbin/kldload}"
: "${KLDUNLOAD:=/sbin/kldunload}"
: "${KLDSTAT:=/sbin/kldstat}"
: "${SHA256:=/sbin/sha256}"
: "${MKNOD:=/sbin/mknod}"

: "${CAT:=/bin/cat}"
: "${ECHO:=/bin/echo}"
: "${PRINTF:=/usr/bin/printf}"
: "${GREP:=/usr/bin/grep}"
: "${SED:=/usr/bin/sed}"
: "${SLEEP:=/bin/sleep}"
: "${PGREP:=/bin/pgrep}"
: "${KILL:=/bin/kill}"
: "${RM:=/bin/rm}"
: "${CU:=/usr/bin/cu}"

: "${GRUB_BHYVE:=${LOCALBASE}/sbin/grub-bhyve}"

DISK_IMAGE="${PREFIX}/share/wifibox/disk.img"

NMDM_DEVICE=/dev/nmdm-wifibox
NMDM_A="${NMDM_DEVICE}.1A"
NMDM_B="${NMDM_DEVICE}.1B"

WIFIBOX_IF="wifibox0"
WIFIBOX_VM="wifibox"

check_virtfs() {
    if ! (${BHYVE} -s help | ${GREP} -Fq virtio-9p); then
	${ECHO} "ERROR: The Virtio 9p (VirtFS) bhyve interface is not available."
	exit 127
    fi
}

sysctl_value() {
    ${SYSCTL} -nq "$1"
}

assert_kmod_loaded() {
    local _kmod="$1"
    local _kmod_file="$2"

    if ! ${KLDSTAT} -q -m "${_kmod}"; then
	if ! ${KLDLOAD} "${_kmod_file}"; then
	    ${ECHO} "ERROR: ${_kmod_file} could not be loaded."
	    exit 127
	fi
    fi
}

# shellcheck disable=SC2046
check_iommu() {
    local _iommu
    local _amdvi

    _iommu=$(sysctl_value "hw.vmm.iommu.enable" || ${ECHO} "0")
    _amdvi=$(sysctl_value "hw.vmm.amdvi.enable" || ${ECHO} "0")

    if [ "${_iommu}" -eq "0" ] && [ "${_amdvi}" -eq "0" ]; then
	${ECHO} "ERROR: PCI pass-through is not available for bhyve."
	exit 127
    fi
}

assert_vm_can_run() {
    assert_kmod_loaded "vmm" "${VMM_KO}"
    check_iommu
    check_virtfs
}

get_image_checksum() {
    ${SHA256} -q "${DISK_IMAGE}"
}

check_configuration() {
    local _file="$1"

    if [ ! -f "${_file}" ]; then
	${ECHO} "ERROR: ${_file} is missing, please create it from the sample."
	exit 3
    fi
}

get_tap_interface() {
    if (${IFCONFIG} | ${GREP} -Fq "${WIFIBOX_IF}: "); then
	${IFCONFIG} "${WIFIBOX_IF}" | ${GREP} -F member | ${SED} -E 's/^.*member:.*(tap[^ ]*).*$/\1/'
    else
	${ECHO} ""
    fi
}

create_bridge() {
    local _tap

    ${IFCONFIG} bridge create name ${WIFIBOX_IF} up > /dev/null
    _tap="$(${IFCONFIG} tap create up)"
    ${IFCONFIG} ${WIFIBOX_IF} addm "${_tap}" > /dev/null
}

destroy_bridge() {
    local _tap

    _tap="$(get_tap_interface)"
    ${IFCONFIG} ${WIFIBOX_IF} destroy > /dev/null

    if [ -n "${_tap}" ]; then
	${IFCONFIG} "${_tap}" destroy > /dev/null
    fi
}

create_nmdm() {
    check_configuration "${CONFDIR}/bhyve.conf"

    # shellcheck source=./etc/bhyve.conf.sample
    . "${CONFDIR}/bhyve.conf"

    [ "${console}" != "yes" ] && return 0

    assert_kmod_loaded "nmdm" "nmdm.ko"

    [ ! -c ${NMDM_A} ] && ${MKNOD} ${NMDM_A}
    [ ! -c ${NMDM_B} ] && ${MKNOD} ${NMDM_B}
}

destroy_nmdm() {
    [ -c ${NMDM_A} ] && ${RM} ${NMDM_A}
    [ -c ${NMDM_B} ] && ${RM} ${NMDM_B}
}

get_ppt_device() {
    check_configuration "${CONFDIR}/bhyve.conf"
    passthru=

    # shellcheck source=./etc/bhyve.conf.sample
    . "${CONFDIR}/bhyve.conf"

    if [ -z "${passthru}" ]; then
	${ECHO} ""
    else
	${ECHO} "pci${passthru}" | ${SED} 's!/!:!g'
    fi
}

get_vm_pid() {
    local _process

    _process="$(basename ${BHYVE})"
    ${PGREP} -fx "${_process}[: ].* ${WIFIBOX_VM}"
}

destroy_vm() {
    ${BHYVECTL} --destroy --vm=${WIFIBOX_VM} >> ${BHYVE_LOG} 2>&1
    ${SLEEP} 1 > /dev/null

    _ppt="$(get_ppt_device)"
    if [ -n "${_ppt}" ]; then
	${DEVCTL} clear driver -f "${_ppt}" > /dev/null
    fi
}

# shellcheck disable=SC2086
vm_start() {
    local _nmdm_grub_bhyve
    local _nmdm_bhyve
    local _passthru_bhyve
    local _tap_bhyve
    local _ppt
    local _tap

    check_configuration "${CONFDIR}/bhyve.conf"
    check_configuration "${CONFDIR}/interfaces.conf"
    check_configuration "${CONFDIR}/udhcpd.conf"
    check_configuration "${CONFDIR}/wpa_supplicant.conf"

    cpus=1
    memory=128M
    passthru=
    console=no

    # shellcheck source=./etc/bhyve.conf.sample
    . "${CONFDIR}/bhyve.conf"

    if [ "${console}" = "yes" ]; then
	_nmdm_grub_bhyve="-c ${NMDM_A}"
	_nmdm_bhyve="-l com1,${NMDM_A}"
    fi

    if [ -n "${passthru}" ]; then
	_passthru_bhyve="-s 6:0,passthru,${passthru}"
    fi

    _ppt="$(get_ppt_device)"
    if [ -n "${_ppt}" ]; then
	${DEVCTL} set driver -f "${_ppt}" ppt > /dev/null
    fi

    _tap="$(get_tap_interface)"
    if [ -n "${_tap}" ]; then
	_tap_bhyve="-s 5:0,e1000,${_tap}"
    else
	${ECHO} "ERROR: No tap(4) interface is available."
	exit 5
    fi

    ${GRUB_BHYVE} -S -M "${memory}" -r host \
		  ${_nmdm_grub_bhyve} \
		  -m ${PREFIX}/share/wifibox/device.map \
		  -d ${PREFIX}/share/wifibox \
		  ${WIFIBOX_VM} > ${GRUB_BHYVE_LOG} 2>&1
    ${BHYVE} -c "${cpus}" -m "${memory}" -AHP -u -S \
	     ${_nmdm_bhyve} \
	     -s 0,hostbridge \
	     -s 31,lpc \
	     -s 4:0,virtio-blk,${DISK_IMAGE} \
	     -s 4:1,virtio-9p,config=${CONFDIR},ro \
	     -s 4:2,virtio-9p,var=${RUNDIR}/appliance \
	     ${_tap_bhyve} \
	     ${_passthru_bhyve} \
	     ${WIFIBOX_VM} > ${BHYVE_LOG} 2>&1 &
    # Give some time for bhyve to launch.
    ${SLEEP} 1 > /dev/null

    if [ -z "$(get_vm_pid)" ]; then
	destroy_vm
	destroy_nmdm
	destroy_bridge
	${ECHO} "ERROR: Guest could not be started, check the contents of ${BHYVE_LOG}."
	exit 4
    fi
}

vm_stop() {
    local _ppt

    ${KILL} -SIGTERM "$(get_vm_pid)" > /dev/null
    ${SLEEP} 3 > /dev/null
    ${BHYVECTL} --force-poweroff --vm=${WIFIBOX_VM} >> ${BHYVE_LOG} 2>&1
    destroy_vm
}

assert_vm_runs() {
    if [ -z "$(get_vm_pid)" ]; then
	${ECHO} "wifibox is not running."
	exit 1
    fi
}

show_progress() {
    ${PRINTF} "."
}

wifibox_start() {
    local _pid

    assert_vm_can_run

    _pid="$(get_vm_pid)"
    if [ -n "${_pid}" ]; then
	${ECHO} "wifibox is already running as PID ${_pid}."
	exit 1
    fi

    ${PRINTF} "Launching wifibox"

    create_bridge
    show_progress

    create_nmdm
    show_progress

    vm_start
    show_progress

    # Give some more time for the guest to boot up.
    ${SLEEP} 2 > /dev/null
    ${ECHO} "OK"
}

wifibox_stop() {
    assert_vm_runs

    ${PRINTF} "Stopping wifibox"

    vm_stop
    show_progress

    destroy_nmdm
    show_progress

    destroy_bridge
    show_progress

    ${ECHO} "OK"
}

# This is a workaround to recover from the unfortunate state of the
# wireless device after resume.
kick_vmm() {
    if ! ${KLDUNLOAD} vmm; then
	${ECHO} "ERROR: Some other bhyve guests might be running, vmm.ko could not be unloaded."
	exit 127
    fi
    ${KLDLOAD} "${VMM_KO}"
}

wifibox_resume() {
    assert_vm_runs

    ${PRINTF} "Resuming wifibox"

    vm_stop
    show_progress

    ${SLEEP} 1
    kick_vmm
    show_progress

    vm_start
    ${ECHO} "OK"
}

wifibox_restart() {
    wifibox_stop
    wifibox_start
}

wifibox_status() {
    local _pid

    _pid="$(get_vm_pid)"
    if [ -n "${_pid}" ]; then
	${ECHO} "wifibox is running as PID ${_pid}."
    else
	${ECHO} "wifibox is not running."
	return 1
    fi
}

wifibox_console() {
    if [ ! -c ${NMDM_B} ]; then
	${ECHO} "ERROR: No null-modem device is configured."
	exit 127
    fi

    ${ECHO} 'Connecting, type "~." to leave the session...'
    ${CU} -s 115200 -l ${NMDM_B}
    ${ECHO} "Finished."
}

wifibox_version() {
    ${ECHO} "wifibox version ${VERSION}"
    ${ECHO} "Disk image checksum: $(get_image_checksum)"
}

# Do not execute the main program when sourced.
[ "$0" != "${SCRIPT}" ] && return 0

case "$1" in
    start) wifibox_start;;
    stop) wifibox_stop;;
    resume) wifibox_resume;;
    restart) wifibox_restart;;
    status) wifibox_status;;
    console) wifibox_console;;
    version) wifibox_version;;
    *) ${ECHO} "USAGE: ${SCRIPT} start | stop | restart | resume | status | console | version" ;;
esac
