#!/bin/bash

# according to /usr/include/sysexit.h
EXIT_USAGE_ERROR=64

function usage_exit() {
    echo "Usage: network <COMMAND>"
    echo "COMMAND:"
    echo "  nic                     show current nic of TC"
    echo "  mac <nic>               show nic mac address"
    echo "  ip <nic>                show nic ip address"
    echo "  ip <nic> <addr>         set new ip address to nic"
    echo "  mask <nic>              show netmask of nic"
    echo "  mask <nic> <mask>       set new netmask to nic"
    echo "  gateway <nic>           show gateway of nic"
    echo "  gateway <nic> <gw>      set new gateway to nic"
    echo "  gateway <nic> delete    delete the gateway of nic"
    echo "  dns <nic>               show dns of nic"
    echo "  dns <nic> <dns>         set new gateway to nic"
    echo "  dns <nic> delete        delete the dns of nic"
    echo "  restart <nic>           restart the nic"
    echo "  show <nic>              show the nic information"
    echo ""
    echo "  dhcp                    show dhcp configurations"
    echo "  dhcp start              start dhcp service"
    echo "  dhcp stop               stop dhcp service"
    echo "  dhcp restart            restart dhcp service"
    echo "  dhcp router <addr>      set dhcp router address"
    echo "  dhcp range  <begin> <end> <mask>"
    echo "                          set dhcp subnet range and mask"
    echo ""
    echo "  nameserver add <addr>   add DNS into server /etc/resolve.conf"
    echo "  nameserver del <addr>   del DNS from server /etc/resolve.conf"
    echo ""
    echo "  export                  export configuration files"
    echo "  import <file>           import configurations from file"
    exit $1
}

if [ $# -lt 1 ]; then
    usage_exit $EXIT_USAGE_ERROR
fi

home="/home/tc"

verb=$1
if [ $verb == "nic" ]; then
    grep -E '^nic' "$home/etc/tc.ini" | awk '{print $3}'
    exit
fi

if [ $verb == "dhcp" ]; then
    dhcp_conf="/etc/dnsmasq.conf"
    more_conf="/etc/dnsmasq.more.conf"

    if [ $# == "1" ]; then
        egrep "^interface|^tftp-root" $dhcp_conf
        egrep "^dhcp-option|^dhcp-range" $more_conf
        exit
    fi

    sub_verb=$2

    if [ $sub_verb == "start" ]; then
        # /etc/init.d/dnsmasq restart CentOS 6 only
        # for both of CentOS 6 and CentOS 7.3
        systemctl start dnsmasq
        systemctl enable dnsmasq
        exit
    fi

    if [ $sub_verb == "stop" ]; then
        # /etc/init.d/dnsmasq restart CentOS 6 only
        # for both of CentOS 6 and CentOS 7.3
        systemctl stop dnsmasq
        systemctl disable dnsmasq
        exit
    fi

    if [ $sub_verb == "restart" ]; then
        # /etc/init.d/dnsmasq restart CentOS 6 only
        # for both of CentOS 6 and CentOS 7.3
        systemctl restart dnsmasq
        exit
    fi

    if [ $sub_verb == "router" ]; then
        if [ $# == "3" ]; then
            router=$3
            sed -i "s@^dhcp-option=3,.*@dhcp-option=3,${router}@g" $more_conf
            exit
        fi
    fi

    if [ $sub_verb == "range" ]; then
        if [ $# == "5" ]; then
            begin=$3
            end=$4
            mask=$5
            sed -i "s@^dhcp-range=.*@dhcp-range=${begin},${end},${mask},48h@g" $more_conf
            exit
        fi
    fi

    if [ $sub_verb == "dns" ]; then
        if [ $# == "4" ]; then
            dns_addr=$4
            sip=$($0 ip)
            if [ $3 == "add" ]; then
                sed -i "s@^dhcp-option=6,.*@dhcp-option=6,${dns_addr},${sip}@g" $more_conf
            elif [ $3 == "del" ]; then
                sed -i "s@^dhcp-option=6,.*@dhcp-option=6,${sip}@g" $more_conf
            fi
            exit
        fi
    fi
# Finish all DHCP related commands
fi

if [ $verb == "export" ]; then
    timestamp=$(date +%Y%m%d%H%M%S)
    tarball="$home/var/network-${timestamp}.tar"
    tar --create --file=$tarball "/etc/dnsmasq-tftp.conf"
    tar --append --file=$tarball "/etc/dnsmasq-notftp.conf"
    tar --append --file=$tarball "/etc/dnsmasq.more.conf"
    tar --append --file=$tarball "/etc/resolv.conf"
    tar --append --file=$tarball "$home/etc/ethers"
    tar --append --file=$tarball "$home/etc/dnsmasq/dnsmasq.leases"
    # crypt it if using password
    if [ $# -eq 2 ]; then
        echo "encrypt the exported file"
        entarball="$tarball.tc"
        gpg2 -c --batch --no-tty --cipher-algo AES256 --symmetric --homedir "$home/var" --passphrase $2 -o $entarball $tarball
        rm -f $tarball
        echo $entarball
    else
        echo $tarball
    fi
    exit
fi

if [ $verb == "ip" ]; then
    nic=$2
    if [ $# -lt 2 ]; then
        nic=$($0 nic)
        $0 ip $nic
        exit
    fi
    if [ $# == "2" ]; then
        oip=` ip -4 -o addr show $nic | awk '{print $4}' | awk -F/ '{print $1}'`
        echo "$oip"
        exit
    else
        nip=$3
        sed -i "/IPADDR/c IPADDR=$nip" "/etc/sysconfig/network-scripts/ifcfg-$nic"
        sed -i "s/tcserver=[0-9\.]* /tcserver=$nip /" "$home/tftpboot/pxelinux.cfg/default"
        sed -i "/ipv4/c ipv4 = $nip" "$home/etc/tcs-env"
        sed -i "/option=6/c dhcp-option=6,$nip" "/etc/dnsmasq.more.conf"
        sed -i "/console.tc/c $nip  console.tc #added by TC web console" "/etc/hosts"
        ifconfig $nic $nip
        exit
    fi
fi

if [ $verb == "mac" ]; then
    nic=$2
    if [ $# -lt 2 ]; then
        nic=$($0 nic)
        $0 mac $nic
        exit
    fi
    if [ $# == "2" ]; then
        cat "/sys/class/net/$nic/address"
        exit
    fi
fi

if [ $verb == "gateway" ]; then
    nic=$2
    cfg="/etc/sysconfig/network-scripts/ifcfg-$nic"
    if [ $# -lt 2 ]; then
        nic=$($0 nic)
        $0 gateway $nic
        exit
    fi
    if [ $# == "2" ]; then
        grep GATEWAY $cfg | awk -F= '{print $2}'
        exit
    fi
    if [ $# -eq 3 ]; then
        gw=${3//./\\.}
        if [ $gw == "delete" ]; then
            sed -i "/^GATEWAY.*/d" $cfg
        else
            grep -q "GATEWAY" "$cfg"
            if [ $? -eq 0 ]; then
                sed -i "/GATEWAY/c GATEWAY=$gw" $cfg
            else
                sed -i "$ a GATEWAY=$gw" $cfg
            fi
        fi
        exit
    fi
fi

if [ $verb == "dns" ]; then
    nic=$2
    cfg="/etc/sysconfig/network-scripts/ifcfg-$nic"
    if [ $# -lt 2 ]; then
        nic=$($0 nic)
        $0 dns $nic
        exit
    fi
    if [ $# == "2" ]; then
        grep DNS1 $cfg | awk -F= '{print $2}'
        exit
    fi
    if [ $# -eq 3 ]; then
        dns1=${3//./\\.}
        if [ $dns1 == "delete" ]; then
            sed -i "/^DNS1.*/d" $cfg
        else
            grep -q "DNS1" "$cfg"
            if [ $? -eq 0 ]; then
                sed -i "/DNS1/c DNS1=$dns1" $cfg
            else
                sed -i "$ a DNS1=$dns1" $cfg
            fi
        fi
        exit
    fi
fi


if [ $# -lt 2 ]; then
    usage_exit $EXIT_USAGE_ERROR
fi

if [ $verb == "import" ]; then
    tarball=$2
    if [ $# -eq 3 ]; then
        detarball="$tarball.tar"
        rm -f $detarball
        gpg2 -d -o $detarball --no-tty --batch --quiet --passphrase $3 "$tarball"
        eno=$?
        if [ $eno -ne 0 ]; then
            echo "Bad password, import failed"
            exit $eno
        fi
        tarball=$detarball
    fi
    tmp="$home/var"
    tar xmf $tarball -C $tmp
    systemctl stop dnsmasq
    if [ -f "$tmp/etc/dnsmasq-tftp.conf" ]; then
        rm -f /etc/dnsmasq-tftp.conf
        cp -fv "$tmp/etc/dnsmasq-tftp.conf" "/etc/dnsmasq-tftp.conf"
    fi
    if [ -f "$tmp/etc/dnsmasq-notftp.conf" ]; then
        rm -f /etc/dnsmasq-notftp.conf
        cp -fv "$tmp/etc/dnsmasq-notftp.conf" "/etc/dnsmasq-notftp.conf"
    fi
    if [ -f "$tmp/etc/dnsmasq.more.conf" ]; then
        rm -f /etc/dnsmasq.more.conf
        cp -fv "$tmp/etc/dnsmasq.more.conf" "/etc/dnsmasq.more.conf"
    fi
    if [ -f "$tmp/home/tc/etc/ethers" ]; then
        rm -f "$home/etc/ethers"
        rm -f /etc/ethers
        cp -fv "$tmp/home/tc/etc/ethers" "$home/etc/ethers"
        ln -s "$home/etc/ethers" "/etc/ethers"
    fi
    if [ -f "$tmp/etc/resolv.conf" ]; then
        rm -f /etc/resolv.conf
        cp -fv "$tmp/etc/resolv.conf" "/etc/resolv.conf"
    fi
    if [ -d "$tmp/etc" ]; then
        rm -rf "$tmp/etc"
    fi
    systemctl start dnsmasq
    exit
fi

if [ $verb == "mask" ]; then
    nic=$2
    cfg="/etc/sysconfig/network-scripts/ifcfg-$nic"
    if [ $# == "2" ]; then
        grep NETMASK $cfg | awk -F= '{print $2}'
        exit
    fi
    if [ $# -eq 3 ]; then
        mask=${3//./\\.}
        sed -i "/NETMASK/c NETMASK=$mask" $cfg
        exit
    fi
fi

if [ $verb == "show" ]; then
    nic=$2
    module=`ethtool -i $nic | awk '/driver/ {print $2}'`
    driver=`modinfo $module | awk '/description/ {a=index($0,$2);print substr($0,a)}'`
    speed=$(cat "/sys/class/net/$nic/speed")
    if [ $# -eq 2 ]; then
        echo "Module: $module"
        echo "Driver: $desc"
        echo "Speed : $speed Mb/s"
        exit
    fi
    if [ $3 == "module" ]; then
        echo $module
        exit
    fi
    if [ $3 == "driver" ]; then
        echo $driver
        exit
    fi
    if [ $3 == "speed" ]; then
        echo $speed
        exit
    fi
    exit
fi

if [ $verb == "restart" ]; then
    nic=$2
    ifdown $nic
    ifup $nic
    exit
fi

#
# edit /etc/resolv.conf directly
#
if [ $verb == "nameserver" ]; then
    if [ $# == "3" ]; then
        resolv="/etc/resolv.conf"
        dns_addr=$3
        if [ $2 == "add" ]; then
            # insert as the first line
            # sed -i "1s/^/nameserver $dns_addr\n/" $resolv
            # 
            # append as the last line
            sed -i "$ a nameserver $dns_addr" $resolv
        elif [ $2 == "del" ]; then
            sed -i "/^nameserver $dns_addr/d" $resolv
        fi
        exit
    fi
fi


usage_exit $EXIT_USAGE_ERROR