#!/bin/bash

if [ `id -u` -ne 0 ]; then
  echo "This script needs to be run as root"
  exit
fi;

if [ $# -lt 1 ]; then
  echo "Usage: $(basename $0) <primary interface>"
  exit
fi;


iface=$1
COLUMNS=78
prefix=${2:-/etc/network/interfaces.d}

valid_ip() {
  local ip=$1
  local stat=1

  if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    OIFS=$IFS
    IFS='.'
    ip=($ip)
    IFS=$OIFS
    [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
      && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
    stat=$?
  fi
  return $stat
}

valid_ips() {
  OIFS=$IFS
  IFS=' '
 for i in $1; do
    valid_ip $i || return 0;
  done
  IFS=$OIFS
}

mask2cdr()
{
  # 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) ))
}

cdr2mask()
{
  # Number of args to shift, 255..255, first non-255 byte, zeroes
  set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0 0
  [ $1 -gt 1 ] && shift $1 || shift
  echo ${1-0}.${2-0}.${3-0}.${4-0}
}

ip_nm() {
  ip a l dev $1|grep "inet "|head -1|awk '{print $2}'
}

iponly() {
  echo $1 |cut -d/ -f1
}

cidr() {
  echo $1 |cut -d/ -f2
}

gateway() {
  ip r|grep default|awk '{print $3}'
}

nameservers() {
  grep nameserver /etc/resolv.conf|awk '{print $2}'|sed 's,\n, ,g'
}

fqdn2host() {
  echo $1|cut -f1 -d.
}

fqdn2domain() {
  echo $1|cut -f2- -d. -s
}

guess_fqdn() {
  fqdn=$(hostname --fqdn)
  host=$(fqdn2host $fqdn)
  domain=$(fqdn2domain $fqdn)
  if [ "$domain" == "" ]; then
    # syntax: "domain foo.com". We only want one
    domain=$(grep domain /etc/resolv.conf|head -1|awk '{ print $2 }')
    if [ "$domain" == "" ]; then
      # syntax: "search foo.com bar.com baz.com". We only want one
      domain=$(grep search /etc/resolv.conf|head -1|awk '{ print $2 }')
    fi
    if [ "$domain" != "" ]; then
    fqdn=$host.$domain
    fi
  fi
  echo $fqdn
}

set_fqdn() {
  fqdn=$1
  host=$(fqdn2host $fqdn)
  entry="127.0.1.1\t$fqdn $host"
  localip="127.0.1.1"
  localip_esc="127\.0\.1\.1"
  grep -q "$localip" /etc/hosts
  if [ $? ]; then
    sed -i 's/'"${localip_esc}"'.*/'"${entry}"'/g' /etc/hosts
  else
    sed -i '1 i\'"${entry}" /etc/hosts
  fi
}

query_ip() {
  text="Enter the IP address for $iface"
  whiptail --inputbox "$text" 8 $COLUMNS $(iponly $(ip_nm $1))
}

query_netmask() {
  text="Enter the netmask for eth0"
  whiptail --inputbox "$text" 8 $COLUMNS $(cdr2mask $(cidr $(ip_nm $1)))
}

query_gateway() {
  text="Enter IP of the default gateway"
  whiptail --inputbox "$text" 8 $COLUMNS $(gateway)
}

query_nameservers() {
  text="Enter IP of one or more name servers, separated by space."
  whiptail --inputbox "$text" 8 $COLUMNS $(nameservers)
}

query_fqdn() {
  text="Enter the hostname, including the domain (e.g. owncloud.example.net):"
  whiptail --inputbox "$text" 8 $COLUMNS $(guess_fqdn)
}

write_dhcp_interface_section() {
 iface=$1
 file=$2
 cat > $prefix/$file << EOF
# Created by ownCloud Appliance setup. Do not modify!

auto  $iface
iface $iface inet dhcp
EOF
}

write_static_interface_section() {
  ip=$1
  netmask=$2
  gateway=$3
  dns=$4
  iface=$5
  file=$6

  cat > $prefix/$file << EOF
# Created by ownCloud Appliance setup. Do not modify!

auto  $iface
iface $iface inet static
    address   $ip
    netmask   $netmask
    gateway   $gateway
    dns-nameservers $dns
EOF
}

# Put on a show :)
restart_iface() {
  (echo 10;
  ifdown $iface; 1>/dev/null 2>&1;
  echo 40;
  $1
  echo 60;
  ifup $iface 1>/dev/null 2>&1;
  echo 100;
  sleep 1)|whiptail --gauge "Restarting interface $iface..." 8 $COLUMNS 0
}

main() {
text="Choose a network configuration type"
conftype=$(whiptail --title "Network configuration" --menu "$text" 10 $COLUMNS 0\
                                                "DHCP" "Automatically configure using DHCP" \
                                                "static" "Enter a static configuration" \
                                                3>&1 1>&2 2>&3)
if [ "$conftype" == "static" ]; then
  until [ "$ip" != "" ] && valid_ip "$ip"; do
    ip=$(query_ip $iface 3>&1 1>&2 2>&3)
    [ $? -eq 1 ] && return
  done;

  until [ "$netmask" != "" ] && valid_ip "$netmask"; do
    netmask=$(query_netmask $iface 3>&1 1>&2 2>&3)
    [ $? -eq 1 ] && return
  done;

  until [ "$gateway" != "" ] && valid_ip "$gateway"; do
    gateway=$(query_gateway 3>&1 1>&2 2>&3)
    [ $? -eq 1 ] && return
  done;

  until [ "$dns" != "" ] && valid_ips "$dns"; do
    dns="$(query_nameservers 3>&1 1>&2 2>&3)"
    [ $? -eq 1 ] && return
  done;

  until [ "$fqdn" != "" ]; do
    fqdn="$(query_fqdn 3>&1 1>&2 2>&3)"
    [ $? -eq 1 ] && return
  done;

  set_fqdn $fqdn

  restart_iface "write_static_interface_section $ip $netmask $gateway $dns $iface ${iface}.cfg";
else
  restart_iface "write_dhcp_interface_section $iface ${iface}.cfg";
fi
}

main
