#!/bin/bash
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

prog=`basename $0 .bash`
PREFIX=/usr/local
ROLE=toxcore

. /usr/local/bin/usr_local_tput.bash || exit 2

MYID=`id -u`
# or use sudo? or just diagnostics? $prog should be run as root $MYID
[ $MYID -eq 0 ] && sudo= || sudo=sudo # "WARN  as root - sudo"
TOXCORE_LOG_DIR=$PREFIX/var/log

grep -q iommu=pt /proc/cmdline       || WARN  'iommu=pt not on command line'
grep -q intel_iommu=on /proc/cmdline || WARN  'intel_iommu=on not on command line'

# https://wiki.archlinux.org/index.php/PCI_passthrough_via_OVMF#Setting_up_IOMMU
shopt -s nullglob
if [ $MYID -eq 0 ] ; then
    [ -s "$TOXCORE_LOG_DIR"/iommu_groups.log ] || \
	for g in /sys/kernel/iommu_groups/*; do
	    echo "IOMMU Group ${g##*/}:"
	    for d in $g/devices/*; do
		echo -e "\t$(lspci -nns ${d##*/})"
	    done
	done 2>&1|tee "$TOXCORE_LOG_DIR"/iommu_groups.log

    b=`wc -l "$TOXCORE_LOG_DIR"/iommu_groups.log|sed -e 's/ .*//'`
    [ $? -eq 0 -a -n "$b" -a "$b" -gt 0 ] || dmesg | grep -q 'DMAR: IOMMU enabled' || WARN  'IOMMU not active'
fi

if ifconfig -a | grep ^eth ; then
    INFO  eth present
else
    WARN  eth NOT present
    lspci -v | grep '0[1-9]:00.0 Ethernet controller'  || {
	WARN  Ethernet NOT present
	rmmod r8169
	modprobe r8169 debug=6
    }
fi

#4?
MODS=(
	ip_tables
	iptable_filter
	iptable_nat
	iptable_mangle

	ipt_REJECT

	nf_conntrack
	nf_defrag_ipv4
#5?	nf_log_common
#5?	nf_log_syslog
	nf_log_ipv4
	nf_nat

	nf_reject_ipv4
	nft_masq

	xt_MASQUERADE
	x_tables

	bridge
	br_netfilter
)
# bridge: filtering via arp/ip/ip6tables is no longer available by default.
# Update your scripts to load br_netfilter if you need this.
lsmod | sort > /tmp/$$.lsmod

# selectively activate runtime features
[ "$#" -eq 0 ] && exit 0

if [ "$1" = "libvirt" -i  "$1" = "libvirt_qemu" ] ; then
    if [ ! -d /dev/virtio-ports ] ; then
	# firewall - should depend on mode
	for mod in "${MODS[@]}" ; do
	    grep -q ^$mod /tmp/$$.lsmod || $sudo modprobe $mod
	done
	rm -f /tmp/$$.lsmod
	ifconfig -a | grep virbr0 || {
	    WARN virbr0 not present - modprobe "${MODS[@]}" ; }
    else
	lsmod | grep -q virtio_console || $sudo modprobe virtio_console 
    fi
  fi
if [ "$1" = "qemu" ] ; then
    if [ ! -d /dev/virtio-ports ] ; then
	lsmod | grep -q kvm || $sudo modprobe kvm
    fi
    exit 0
  fi

if [ "$1" = "docker" ] ; then
    #? modules for docker?
    exit 0
  fi

exit 0

