#!/bin/bash -e
# vim: set ts=4 sw=4 sts=4 et :
#
# network-proxy-setup - Enables an extra internal network interface
#
# 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/>.

set -x

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

qubes_vm_type="$(qubesdb-read /qubes-vm-type)"

if [ "$qubes_vm_type" = "TemplateVM" ]; then
   ## Do none of the following in a TemplateVM.
   exit 0
fi

if [ ! -e /usr/share/anon-gw-base-files/gateway ]; then
   ## Proceed only in Whonix-Gateway.
   exit 0
fi

# network="$(qubesdb-read /qubes-netvm-network)"
#
# if [ ! "$network" = "" ]; then
#    gateway="$(qubesdb-read /qubes-netvm-gateway)"
#    primary_dns="$(qubesdb-read /qubes-netvm-primary-dns)"
#    if [ "$primary_dns" = "" ]; then
#       primary_dns="$gateway"
#    fi
#    secondary_dns="$(qubesdb-read /qubes-netvm-secondary-dns)"
#    ## Qubes original /lib/qubes/qubes-setup-dnat-to-ns uses this,
#    ## but Whonix (config-package-dev 'displace'ed)
#    ## /lib/qubes/qubes-setup-dnat-to-ns.anondist-orig does not use it.
#    echo "NS1=$primary_dns" > /run/qubes/qubes-ns
#    echo "NS2=$secondary_dns" >> /run/qubes/qubes-ns
# fi

## TODO: https://phabricator.whonix.org/T857
/sbin/ethtool -K eth0 sg off || true

INTERFACE="eth1"

if ip link show "$INTERFACE" ; then
   exit 0
fi

## Now, assign it the netvm-gateway IP address
ip="$(qubesdb-read /qubes-netvm-gateway)"

if [ ! "$ip" = "" ]; 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 /qubes-netvm-netmask)"
   /sbin/ifconfig "$INTERFACE" "$ip" netmask "$netmask"
   /sbin/ifconfig "$INTERFACE" up

   ## TODO: https://phabricator.whonix.org/T857
   /sbin/ethtool -K "$INTERFACE" sg off || true
   /sbin/ethtool -K "$INTERFACE" tx off || true

   ip link set "$INTERFACE" up
fi
