#!/bin/bash
#
#  Copyright 2012, One Laptop per Child
#  Author: Jerry Vonau, George Hunt
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library 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 Library General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

PLUGINDIR=/usr/share/xs-config/plugins.d
SYSCONFIGDIR="/etc/sysconfig"
LOG=/var/log/xs-setup.log

# Parse options

opt_upgrade_only=
if ! options=$(getopt -o u -l upgrade-only -- "$@"); then
	exit 1
fi

eval set -- $options
while [ $# -gt 0 ]; do
	case $1 in
		-u|--upgrade-only) opt_upgrade_only=1 ;;
		(--) shift; break;;
		(-*) echo "$0: error - unrecognized option $1" >&2; exit 1;;
		(*) break;;
	esac
	shift
done

# The user can request that we only perform setup steps if setup had been
# previously performed by an admin. This is useful for automated upgrades
# (e.g. RPM post scripts).
if [ -n "$opt_upgrade_only" ]; then
	echo "$0: doing nothing, XS standard networking is not active."
	exit 0
fi

# for public demo, disable any functions that would change the machine state
if [ -f /etc/sysconfig/xs-disable-config ]; then
    echo ""
    echo "======================================================"
    echo
    echo "This public demonstration server cannot be configured remotely"
    echo
    echo "======================================================"
    exit 0
fi

# silence noisy logging from missing file
if ! [ -f /etc/sysconfig/network-scripts/net.hotplug ]; then
    echo "#!/bin/bash" > /etc/sysconfig/network-scripts/net.hotplug
    chmod 700 /etc/sysconfig/network-scripts/net.hotplug
fi

# Determine the number of interfaces
num_ifaces=`ls /sys/class/net | wc | gawk '{print $1}'`

# Is this an XO
is_xo=`[ -f /proc/device-tree/mfg-data/MN ] && echo 1 || echo 0`
echo "is_xo = $is_xo" | tee -a $LOG

function delete_eth0_connections
# removes any stored connection for wifi, (on an XO only)
# the down side is that the software key will need to be entered again
{
    if [ -n "$1" ]; then
        for connection in $1;do
            if [ grep "802-11-wireless" $connection ]; then
                echo "removing $connection" | tee -a $LOG
                rm -f $connection | tee -a $LOG
            fi
        done
    fi
}

function clean_connection
# removes all un-used connection names that we care about
# takes type and interface
{
    list=`ls /etc/NetworkManager/system-connections/*-$1` 2>&1 >/dev/null
    echo "found old connections: $list" | tee -a $LOG
    if [ "$list" != /etc/NetworkManager/system-connections/$2-$1 ]; then
        for connection in $list;do
            echo "removing $connection" | tee -a $LOG
            rm -f $connection | tee -a $LOG
        done
    else
        echo "not removing $2-$1 over-writing" | tee -a $LOG
    fi
}

# use NetworkManager to set up devices
function write_nm_connection(){
    # receives connection_filename, hwaddr,  device_name as parameters
    new_uuid=`uuidgen`
    cp "/usr/share/xs-config/cfg/etc/NetworkManager/system-connections/$1" \
        "/etc/NetworkManager/system-connections/$3-$1"
    sed -i  "s/\@\@MAC\@\@/$2/" "/etc/NetworkManager/system-connections/$3-$1"
    sed -i  "s/\@\@DEVICE\@\@/$3/" "/etc/NetworkManager/system-connections/$3-$1"
    sed -i  "s/\@\@UUID\@\@/$new_uuid/" "/etc/NetworkManager/system-connections/$3-$1"
    if [ $1 = "static" ]; then
        domain_name=`hostname -d`
        sed -i  "s/@@DOMAIN@@/$domain_name/" "/etc/NetworkManager/system-connections/$3-$1"
    fi
    chmod 600 "/etc/NetworkManager/system-connections/$3-$1"
    echo "write_nm_connection wrote $3-$1 with mac addr $2" | tee -a $LOG
}

#========================================================

pushd /etc
CFG_TEMPLATES="sysconfig/dhcpd sysconfig/iptables-config sysconfig/ip6tables-config"
for i in $CFG_TEMPLATES; do
	cp -p $i.in $i
	#etckeeper commit -m "Made from $i.in"
done
popd

# If there is only one card it will be wan if there is a gateway otherwise it will be lan
# If there are more than 2 cards, the last non-gateway one will be lan

# Try to figure out which interface is connected to a gateway
gw_iface=`route -n | awk '{if($4=="UG")print $8}'`
gw_mac=`ifconfig $gw_iface | gawk '(/^ *ether /) {print( $2);}'`
gw_ip=`ifconfig $gw_iface | gawk '(/netmask /) {print( $2);}'`

# Pick a another card, any card (except lo and gw_iface, if not null)
for iface in $(ifconfig | gawk 'BEGIN{FS=":"}(/^.*: flags=/) {print( $1);}')
    do
    if [ "$iface" != "lo" ] && [ "$iface" != "$gw_iface" ]; then
       oth_iface=$iface
    fi
done

## start LAN
if [ $is_xo = 1 ];then
    XO4=`cat /proc/device-tree/mfg-data/MN | grep XO-4` 
else
    XO4=
fi    

# mlan0 comes after eth2 so the above would be wrong on a XO-4
if [ $num_ifaces -gt 3 ] && [ x"$XO4" != x ]; then
    echo "Forcing LAN to be eth2 on XO-4" | tee -a $LOG
    oth_iface=eth2
fi

if [ -n $oth_iface ]; then
    oth_mac=`ifconfig $oth_iface | gawk '(/^ *ether /) {print( $2);}'`
    clean_connection static $oth_iface
    write_nm_connection "static" "$oth_mac" "$oth_iface"
    echo "$oth_iface" > /etc/sysconfig/xs_lan_device
    echo "$oth_mac" > /etc/sysconfig/xs_lan_mac
    ipaddr=172.18.96.1
    sed -i -e s/@@LAN_IF@@/$oth_iface/ /etc/sysconfig/dhcpd
    echo "LAN device $oth_iface using $ipaddr " | tee -a $LOG
else
    ## need to have ports open to lan via iptables
    ## if there is no $oth_iface then wan is lan
    echo "$gw_iface" > /etc/sysconfig/xs_lan_device
    echo "$gw_mac" > /etc/sysconfig/xs_lan_mac
    ipaddr=$gw_ip
fi

#========================================================
# 4/14/13   then abort further processing if device names and mac numbers are unchanged
source "$PLUGINDIR/network/network.sh"
if [ ! is_network_changed ]; then
    echo "xs-setup-network should not continue no changes detected" | tee -a $LOG
    return 0
fi
# end 4/14/13========================================================

if [ -n "$gw_iface" ]; then
    wan_iface=$gw_iface
    wan_mac=$gw_mac
    wan_ip=$gw_ip
    echo "gateway device $gw_iface using $wan_ip" | tee -a $LOG
    if [ $is_xo -eq 0 ]; then
        clean_connection dhcp $wan_iface
        write_nm_connection "dhcp" "$wan_mac" "$wan_iface"
    fi

    UPLINK=`find /etc/NetworkManager/system-connections -maxdepth 1 -type f -name "*" \
            -not -name *static -not -name "Sugar *"`
    if [ $is_xo -eq 1 ]; then
	case $wan_iface in
            eth0|mlan0)
                for i in $UPLINK;
                do
                    present=`cat $i | grep ignore-auto-dns=true`
                    if [ x$present = x ]; then
                        sed -i '/method=auto/d' $i 
                        sed -i '/ipv4/d' $i 
                        sed -i '/ipv6/d' $i 
                        echo "[ipv6]" >> $i
                        echo "method=auto" >> $i
                        echo "" >> $i
                        echo "[ipv4]" >> $i
                        echo "method=auto" >> $i
                        echo "ignore-auto-dns=true" >> $i
                    else
                        echo "ignore-auto-dns=true already present for $i" | tee -a $LOG
                    fi
                done
                ;;
            *)
                clean_connection dhcp $wan_iface
                write_nm_connection "dhcp" "$wan_mac" "$wan_iface"
                # if we have two dongles, disable the internal radio
                if [ x"$UPLINK" != x  ]; then
                    delete_eth0_connections $UPLINK
                fi
                ;;
        esac

    fi # end of dealing with is_xo
    echo "$wan_iface" > /etc/sysconfig/xs_wan_device
    echo "$wan_mac" > /etc/sysconfig/xs_wan_mac
fi

# the dhclient attaches to the wan device, fixup may be necessary
if [ "$last_wan_dev" != "$wan_iface" ];then
    /usr/share/xs-config/cfg/etc/dhcp/dhclient
fi

nmrpm=`rpm -q NetworkManager | awk -F - '{print $2}' | sed -e 's/\.//' \
       | sed -e 's/\.//' | sed -e 's/\.//'` 
echo "NetworkManager version is $nmrpm" | tee -a $LOG
if [ $nmrpm -gt 0981 ];then
    systemctl enable NetworkManager-dispatcher.service 2>&1 | tee -a $LOG
    systemctl stop NetworkManager-dispatcher.service 2>&1 | tee -a $LOG
fi
systemctl stop NetworkManager.service 2>&1 | tee -a $LOG
systemctl start NetworkManager.service 2>&1 | tee -a $LOG

if [ $nmrpm -gt 0981 ];then
    systemctl start NetworkManager-dispatcher.service 2>&1 | tee -a $LOG
fi

short_host=`hostname -s`
new_name=`hostname -f`
#new_name=`hostname `

#  This is the suffix which original versions of modified files will have
BACKUP_SUFFIX=old

CONFIG_LIST="/etc/hosts"
for config in $CONFIG_LIST;
do
    if [ -e $config.in ]; then
	if [ -e $config ]; then
	    cp $config $config.$BACKUP_SUFFIX ;
	fi
	cp $config.in $config.tmp ;
	sed -i -e s/@@BASEDNSNAME4@@/$short_host/ $config.tmp ;
	sed -i -e s/@@BASEDNSNAME3@@/$short_host/ $config.tmp ;
	sed -i -e s/@@BASEDNSNAME2@@/$new_name/ $config.tmp ;
	sed -i -e s/@@IPADDR@@/$ipaddr/ $config.tmp ;
	cat $config.tmp > $config ;
	rm $config.tmp ;
	#etckeeper commit -m "set /etc/hosts to $ipaddr $new_name $short_host"
    else
	echo WARNING: Skipped $config - template file is missing! | tee -a $LOG
    fi
done

# the adapter names may have changed, so update the iptables
set +e
#/bin/xs-gen-iptables 2>&1 | tee -a $LOG
/etc/sysconfig/iptables-config  2>&1 | tee -a $LOG
systemctl restart iptables.service 2>&1 | tee -a $LOG
set -e
echo "################################################################"  | tee -a $LOG
echo "XS standard networking configured with" | tee -a $LOG
echo "hostname = $short_host" | tee -a $LOG
echo "FQDN = $new_name" | tee -a $LOG
echo "LAN device $oth_iface using $ipaddr " | tee -a $LOG
echo "gateway device $gw_iface using $wan_ip" | tee -a $LOG
echo "################################################################"  | tee -a $LOG
mydate=`date`
echo "completed the xs-setup-network script at $mydate" | tee -a $LOG

