#!/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


# FixMe - systemd


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

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
    }
    true || [ -f /var/lib/libvirt/net.xml ] || cat > /var/lib/libvirt/net.xml << EOF
<network>
  <name>network</name>
  <uuid>3f1b2eb3-98da-4e6d-8ad8-30e0e05a21d4</uuid>
  <forward mode="nat"/>
  <bridge name="virbr0" stp="on" delay="0"/>
  <mac address="52:54:00:14:17:cf"/>
  <domain name="network"/>
  <ip address="192.168.100.1" netmask="255.255.255.0">
    <dhcp>
      <range start="192.168.100.128" end="192.168.100.254"/>
    </dhcp>
  </ip>
</network>
EOF
    ifconfig -a |grep ^eth && {
	ifconfig -a |grep ^virbr || {
	    $sudo virsh net-create /var/lib/libvirt/net.xml
	}
    }
fi

#4?
MODS4=(
    nf_conntrack_ipv4
    nf_nat_ipv4
)

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
for mod in "${MODS[@]}" ; do
    grep -q ^$mod /tmp/$$.lsmod || $sudo modprobe $mod
  done
rm -f /tmp/$$.lsmod

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

if [ "$1" = "libvirt" ] ; then
    /etc/init.d/libvirtd status || $sudo /etc/init.d/libvirtd start
    ifconfig -a | grep virbr0 || {
	WARN virbr0 not present - modprobe "${MODS[@]}" ; }
  fi
if [ "$1" = "qemu" ] ; then
    lsmod | grep -q kvm || $sudo modprobe kvm
    exit 0
  fi

if [ "$1" = "docker" ] ; then
    #? modules for docker?
    /etc/init.d/docker status || $sudo /etc/init.d/docker start
    exit 0
  fi

exit 0

