#!/bin/bash -e
# vim: set ts=4 sw=4 sts=4 et :
#
# network-proxy-setup - Enables an extra internal network interface
#
# This file is part of Qubes+Whonix.
# Copyright (C) 2014 - 2015 Jason Mehring <nrgaway@gmail.com>
# License: GPL-2+
# Authors: Jason Mehring
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation; either version 2
#   of the License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

source /usr/lib/qubes-whonix/utility_functions.sh

INTERFACE="eth1"

if [ -e /var/run/qubes-service/whonix-gateway ]; then

    # Setup Xen / Qubes proxy
    network=$(${QUBESDB}-read ${PREFIX}qubes-netvm-network 2>/dev/null)
    if [ "x$network" != "x" ]; then
        gateway=$(${QUBESDB}-read ${PREFIX}qubes-netvm-gateway)
        netmask=$(${QUBESDB}-read ${PREFIX}qubes-netvm-netmask)
        secondary_dns=$(${QUBESDB}-read ${PREFIX}qubes-netvm-secondary-dns)
        modprobe netbk 2> /dev/null || modprobe xen-netback
        echo "NS1=$gateway" > /var/run/qubes/qubes-ns
        echo "NS2=$secondary_dns" >> /var/run/qubes/qubes-ns
        echo "0" > /proc/sys/net/ipv4/ip_forward
        /sbin/ethtool -K eth0 sg off || true
    fi

    # Now, assign it the netvm-gateway IP address
    ip link show ${INTERFACE} &> /dev/null || {
        ip=$(${QUBESDB}-read ${PREFIX}qubes-netvm-gateway 2> /dev/null)
        if [ x${ip} != x ]; then
            # Create a dummy eth1 interface so tor can bind to it if there
            # are no DOMU virtual machines connected at the moment
            ip link add ${INTERFACE} type dummy || true

            netmask=$(${QUBESDB}-read ${PREFIX}qubes-netvm-netmask)
            gateway=$(${QUBESDB}-read ${PREFIX}qubes-netvm-gateway)
            /sbin/ifconfig ${INTERFACE} ${ip} netmask 255.255.255.255
            /sbin/ifconfig ${INTERFACE} up
            /sbin/ethtool -K ${INTERFACE} sg off || true
            /sbin/ethtool -K ${INTERFACE} tx off || true

            ip link set ${INTERFACE} up
        fi
    }
fi
