#!/bin/sh -

distrosysconfdir="/etc/default"
localstatedir="/var"
varrun="/run/fan"

[ ! -f $distrosysconfdir/ubuntu-fan ] || . $distrosysconfdir/ubuntu-fan

if [ -z "${FAN_OVERLAY}" ]; then
	exit 0
fi

if [ -z "${FAN_PRIMARY}" ]; then
	FAN_PRIMARY=`ip route show 0.0.0.0/0 | awk '{print $5; exit}'`
fi

if [ -z "${FAN_PRIMARY_ADDR}" ]; then
	FAN_PRIMARY_ADDR=`ip -4 addr show dev ${FAN_PRIMARY} | grep inet | awk -F '[/ ]*' '{print $3; exit}'`
fi

if [ -z "${FAN_PRIMARY_ADDR}" ]; then
	echo "${FAN_PRIMARY}: interface or address not found" 1>&2
	exit 0
fi

FAN_UNDERLAY=`echo ${FAN_PRIMARY_ADDR} | awk '{split($1, ad1, "."); print ad1[1] "." ad1[2] ".0.0"}'`
FAN_PREFIX=`echo ${FAN_OVERLAY} ${FAN_PRIMARY_ADDR} | awk '{split($1, ad1, "."); split($2, ad2, "."); print ad1[1] "." ad2[3] "." ad2[4] ; }'`
FAN_SUBNET="${FAN_PREFIX}.0/24"

FAN_ADDR="${FAN_PREFIX}.1"
FAN_NETMASK="255.255.255.0"
FAN_NETWORK="${FAN_SUBNET}"
FAN_DHCP_RANGE="${FAN_PREFIX}.2,${FAN_PREFIX}.254"
FAN_DHCP_MAX="253"
FAN_DHCP_CONFILE=""
FAN_DOMAIN=""

set | grep FAN_

if [ -d "$localstatedir"/lock/subsys ]; then
    lockdir="$localstatedir"/lock/subsys
else
    lockdir="$localstatedir"/lock
fi

_netmask2cidr ()
{
    # Assumes there's no "255." after a non-255 byte in the mask
    local x=${1##*255.}
    set -- 0^^^128^192^224^240^248^252^254^ $(( (${#1} - ${#x})*2 )) ${x%%.*}
    x=${1%%$3*}
    echo $(( $2 + (${#x}/4) ))
}

ifdown() {
    which ip >/dev/null 2>&1
    if [ $? = 0 ]; then
        ip link set dev $1 down
	return
    fi
    which ifconfig >/dev/null 2>&1
    if [ $? = 0 ]; then
        ifconfig $1 down
    fi
}

ifup() {
    which ip >/dev/null 2>&1
    if [ $? = 0 ]; then
        MASK=`_netmask2cidr ${FAN_NETMASK}`
        CIDR_ADDR="${FAN_ADDR}/${MASK}"
        ip addr add ${CIDR_ADDR} dev $1
        ip link set dev $1 up
        return
    fi
    which ifconfig >/dev/null 2>&1
    if [ $? = 0 ]; then
        ifconfig $1 $2 netmask $3 up
    fi
}

start() {
    [ ! -f "${lockdir}"/fan-net ] || { exit 0; }

    # Configure the ${FAN_DEV} ipip link and add the wider routes.
    ip link add ${FAN_DEV} type ipip local ${FAN_PRIMARY_ADDR} underlay ${FAN_UNDERLAY} dev ${FAN_PRIMARY}
    ip link set dev ${FAN_DEV} up
    ip route add ${FAN_OVERLAY} dev ${FAN_DEV}

    [ "x$USE_FAN_BRIDGE" = "xtrue" ] || { exit 0; }

    use_iptables_lock="-w"
    iptables -w -L -n > /dev/null 2>&1 || use_iptables_lock=""
    cleanup() {
        # dnsmasq failed to start, clean up the bridge
        iptables $use_iptables_lock -D INPUT -i ${FAN_BRIDGE} -p udp --dport 67 -j ACCEPT
        iptables $use_iptables_lock -D INPUT -i ${FAN_BRIDGE} -p tcp --dport 67 -j ACCEPT
        iptables $use_iptables_lock -D INPUT -i ${FAN_BRIDGE} -p udp --dport 53 -j ACCEPT
        iptables $use_iptables_lock -D INPUT -i ${FAN_BRIDGE} -p tcp --dport 53 -j ACCEPT
        iptables $use_iptables_lock -D FORWARD -i ${FAN_BRIDGE} -j ACCEPT
        iptables $use_iptables_lock -D FORWARD -o ${FAN_BRIDGE} -j ACCEPT
        iptables $use_iptables_lock -t nat -D POSTROUTING --source ${FAN_SUBNET} \! --dest ${FAN_OVERLAY} -j MASQUERADE
        iptables $use_iptables_lock -t mangle -D POSTROUTING -o ${FAN_BRIDGE} -p udp -m udp --dport 68 -j CHECKSUM --checksum-fill
        ifdown ${FAN_BRIDGE}
        brctl delbr ${FAN_BRIDGE} || true
    }

    if [ -d /sys/class/net/${FAN_BRIDGE} ]; then
        exit 0;
    fi

    # set up the fan network
    brctl addbr ${FAN_BRIDGE} || { echo "Missing bridge support in kernel"; stop; exit 0; }
    echo 1 > /proc/sys/net/ipv4/ip_forward

    # if we are run from systemd on a system with selinux enabled,
    # the mkdir will create /run/fan as init_var_run_t which dnsmasq
    # can't write its pid into, so we restorecon it (to var_run_t)
    if [ ! -d "${varrun}" ]; then
        mkdir -p "${varrun}"
        which restorecon >/dev/null 2>&1
        if [ $? = 0 ]; then
            restorecon "${varrun}"
        fi
    fi

    ifup ${FAN_BRIDGE} ${FAN_ADDR} ${FAN_NETMASK}
    ifconfig ${FAN_BRIDGE} mtu 1480

    iptables $use_iptables_lock -I INPUT -i ${FAN_BRIDGE} -p udp --dport 67 -j ACCEPT
    iptables $use_iptables_lock -I INPUT -i ${FAN_BRIDGE} -p tcp --dport 67 -j ACCEPT
    iptables $use_iptables_lock -I INPUT -i ${FAN_BRIDGE} -p udp --dport 53 -j ACCEPT
    iptables $use_iptables_lock -I INPUT -i ${FAN_BRIDGE} -p tcp --dport 53 -j ACCEPT
    iptables $use_iptables_lock -I FORWARD -i ${FAN_BRIDGE} -j ACCEPT
    iptables $use_iptables_lock -I FORWARD -o ${FAN_BRIDGE} -j ACCEPT
    iptables $use_iptables_lock -t nat -A POSTROUTING --source ${FAN_SUBNET} \! --dest ${FAN_OVERLAY} -j MASQUERADE
    iptables $use_iptables_lock -t mangle -A POSTROUTING -o ${FAN_BRIDGE} -p udp -m udp --dport 68 -j CHECKSUM --checksum-fill

    FAN_DOMAIN_ARG=""
    if [ -n "$FAN_DOMAIN" ]; then
        FAN_DOMAIN_ARG="-s $FAN_DOMAIN -S /$FAN_DOMAIN/"
    fi

    # https://lists.linuxcontainers.org/pipermail/lxc-devel/2014-October/010561.html
    for DNSMASQ_USER in fan-dnsmasq dnsmasq nobody
    do
        if getent passwd ${DNSMASQ_USER} >/dev/null; then
            break
        fi
    done
# dnsmasq will complain because the fan route is a supernet of the
# address configured on the bridge. 
    dnsmasq $FAN_DOMAIN_ARG -u ${DNSMASQ_USER} --strict-order --bind-interfaces --pid-file="${varrun}"/dnsmasq.pid --conf-file=${FAN_DHCP_CONFILE} --listen-address ${FAN_ADDR} --dhcp-range ${FAN_DHCP_RANGE} --dhcp-lease-max=${FAN_DHCP_MAX} --dhcp-no-override --except-interface=lo --interface=${FAN_BRIDGE} --dhcp-leasefile=/var/lib/misc/dnsmasq.${FAN_BRIDGE}.leases --dhcp-authoritative || cleanup
    touch "${varrun}"/network_up
    touch "${lockdir}"/fan-net
}

stop() {
    [ "x$USE_FAN_BRIDGE" = "xtrue" ] || { exit 0; }

    [ -f "${varrun}/network_up" ] || { exit 0; }
    # if $FAN_BRIDGE has attached interfaces, don't shut it down
    ls /sys/class/net/${FAN_BRIDGE}/brif/* > /dev/null 2>&1 && exit 0;

    if [ -d /sys/class/net/${FAN_DEV} ]; then
	ifdown ${FAN_DEV}
	ip link delete ${FAN_DEV} type ipip 
    fi

    if [ -d /sys/class/net/${FAN_BRIDGE} ]; then
        use_iptables_lock="-w"
        iptables -w -L -n > /dev/null 2>&1 || use_iptables_lock=""
        ifdown ${FAN_BRIDGE}
        iptables $use_iptables_lock -D INPUT -i ${FAN_BRIDGE} -p udp --dport 67 -j ACCEPT
        iptables $use_iptables_lock -D INPUT -i ${FAN_BRIDGE} -p tcp --dport 67 -j ACCEPT
        iptables $use_iptables_lock -D INPUT -i ${FAN_BRIDGE} -p udp --dport 53 -j ACCEPT
        iptables $use_iptables_lock -D INPUT -i ${FAN_BRIDGE} -p tcp --dport 53 -j ACCEPT
        iptables $use_iptables_lock -D FORWARD -i ${FAN_BRIDGE} -j ACCEPT
        iptables $use_iptables_lock -D FORWARD -o ${FAN_BRIDGE} -j ACCEPT
        iptables $use_iptables_lock -t nat -D POSTROUTING --source ${FAN_SUBNET} \! --dest ${FAN_OVERLAY} -j MASQUERADE
        iptables $use_iptables_lock -t mangle -D POSTROUTING -o ${FAN_BRIDGE} -p udp -m udp --dport 68 -j CHECKSUM --checksum-fill
        pid=`cat "${varrun}"/dnsmasq.pid 2>/dev/null` && kill -9 $pid || true
        rm -f "${varrun}"/dnsmasq.pid
        brctl delbr ${FAN_BRIDGE}
    fi
    rm -f "${varrun}"/network_up
    rm -f "${lockdir}"/fan-net
}

# See how we were called.
case "$1" in
    start)
        start
    ;;

    stop)
        stop
    ;;

    restart|reload|force-reload)
        $0 stop
        $0 start
    ;;

    *)
        echo "Usage: $0 {start|stop|restart|reload|force-reload}"
        exit 2
esac

exit $?
