#!/bin/bash
#
# !!!!!! Tris script must use /bin/bash !!!!!!!!
#

command_name=$0
ipaddress=$1
ipmask=$2
ipgw=$3
ssid=$4
pwd=$5
default_mask="255.255.255.0"

# Detect OS version 
dist=$(lsb_release -si)
ver=$(lsb_release -sr)
nam=$(lsb_release -sc)
desc=$(lsb_release -sd)
kernel=$(uname -r | awk -F '-' '{print $1}')

# Detect hardware
ccpu=$(grep "model name" -m 1 /proc/cpuinfo | awk -F ': ' '{print $2}')
grep -q "Intel(R) Celeron(R) CPU  J1900  @ 1.99GHz"  /proc/cpuinfo
if [ $? -eq 0 ]; then
	cpu="J1900"
else
	grep -q "Intel(R) Atom(TM) CPU N2600   @ 1.60GHz" /proc/cpuinfo
	if [ $? -eq 0 ]; then
		cpu="N2600"
	else
		grep -q "Genuine Intel(R) CPU N270   @ 1.60GHz" /proc/cpuinfo
		if [ $? -eq 0 ]; then
			cpu="N270"
		else
			grep -q "Intel(R) Atom(TM) CPU  330   @ 1.60GHz" /proc/cpuinfo
			if [ $? -eq 0 ]; then
				cpu="330"
			else
				cpu="Generic"
			fi
		fi
	fi
fi

CheckPermission() {
	account=`whoami`
	if [ ${account} != "root" ]; then
		echo " Hi ${account}, you are NOT the supervisor."
		echo " The root permission is required to run this installer."
		echo " You must execute this script with sudo"
		echo ' '
		exit 1
	fi
	echo ' '
	echo "Detected $dist $nam $ver [$desc] with $kernel kernel on $cpu CPU machine"
	echo ' '
	if [ "$cpu" != "N2600" ] && [ "$cpu" != "J1900" ]; then
		echo "$ccpu detected."
		echo "Hardware does not match a proper scale."
		echo ' '
		exit 1
	fi
	if [ "$dist" != "Ubuntu" ]; then
		echo " Linux distribution $dist not supported."
		echo ' '
		exit 1
	fi
	if [ "$ver" != "12.04" ]; then
		echo "Ubuntu version $ver not supported."
		echo "This scipt is designed for $dist Precise [12.04]."
		echo ' '
		exit 1
	fi
}

dec2ip () {
    local ip dec=$1
    for e in {3..0}
    do
        ((octet = dec / (256 ** e) ))
        ((dec -= octet * 256 ** e))
        ip+=$delim$octet
        delim=.
    done
    echo "$ip" | awk -F . '{ print $4"."$3"."$2"."$1}'
}


mask2cidr() {
    local nbits dec
    local -a octets=( [255]=8 [254]=7 [252]=6 [248]=5 [240]=4
                      [224]=3 [192]=2 [128]=1 [0]=0           )
    
    while read -rd '.' dec; do
        [[ -z ${octets[dec]} ]] && echo "Error: $dec is not recognised" && exit 1
        (( nbits += octets[dec] ))
        (( dec < 255 )) && break
    done <<<"$1."

    echo "$nbits"
}

CheckVersion() { 
	echo "$@" | gawk -F. '{ printf("%03d%03d%03d\n", $1,$2,$3); }'; 
}

CheckParameters() {
	if [ "$ipaddress" = "" ]; then
		return 0
	fi
	return 1
}

ShowSyntax() {
	echo ""
	echo "usage: $command_name <address> [<mask> [<gateway>]]"
	#	echo "usage: $command_name <address> [<mask> [<gateway>]] [<ssid> [<security password>]]"
	echo ""
}

# Read connection values
#	param1: connection name
ReadConnectionValues() {
	conn_name=$1
	settings_path=$(nmcli -t -f NAME,DBUS-PATH con | grep "$conn_name" | awk -F ':' '{print $2}')
	addr_base=$(qdbus --system --literal org.freedesktop.NetworkManager $settings_path org.freedesktop.NetworkManager.Settings.Connection.GetSettings |sed 's/, "/\n"/g' | grep -A1 "ipv4" | grep addresses)
	if [ "$ipmask" = "" ]; then
		read_mask=$(echo $addr_base | awk -F ', ' '{ print $2 }')
		if [ "$read_mask" = "" ]; then
			read_mask=$(mask2cidr $default_mask)
		fi
	else
		read_mask=$(mask2cidr $ipmask)
	fi
	if [ "$ipgw" = "" ]; then
		read_gw_uint=$(echo $addr_base | awk -F ', ' '{ print $3}' | awk -F '}' '{ print $1}')
		read_gw=$(dec2ip $read_gw_uint)
		if [ "$read_gw" = "0.0.0.0" ]; then
			read_gw=$(echo $ipaddress | awk -F '.' '{ print $1"."$2"."$3".1" }')
		fi
	else
		read_gw=$ipgw
	fi
}

ConfigureConnection() {
	name=$1
	read_ip=$2
	target="/etc/NetworkManager/system-connections/$name"
	if [ -f "$target" ]; then
		ReadConnectionValues "$name"
		addresses="$read_ip;$read_mask;$read_gw;"
		sed -i -e '/ipv/,$d' $target
		echo "[ipv6]" >> $target
		echo "method=ignore" >> $target
		echo "" >> $target
		echo "[ipv4]" >> $target
		echo "method=manual" >> $target
		echo "dns=8.8.8.8;8.8.4.4;" >> $target
		echo "addresses1=$addresses" >> $target
		echo "ignore-auto-dns=true" >> $target
	fi
}

ConfigureConnections() {
	OLDIFS=$IFS
	IFS=$'\n'
	conns=$(nmcli con | grep 802-3-ethernet | wc -l)
	if [ $conns -ne 0 ]; then
		conn_wired=$(nmcli -t -f name,type con | grep 802-3-ethernet | awk -F ':' '{print $1}')
		echo "Detected wired connection(s)"
		echo "$conn_wired"
		for conn in $conn_wired
		do
			ConfigureConnection "$conn" $ipaddress
		done
	else
		echo No wired connections detected
	fi
	
	conns=$(nmcli con | grep 802-11-wireless | wc -l)
	if [ $conns -ne 0 ]; then
		conn_wireless=$(nmcli -t -f name,type con | grep 802-11-wireless | awk -F ':' '{print $1}')
		echo "Detected wireless connection(s)"
		echo "$conn_wireless"
		for conn in $conn_wireless
		do
			ConfigureConnection $conn $ipaddress
		done
	else
		echo No wireless connections detected
	fi
	IFS=$OLDIFS
}


CheckParameters
if [ $? -eq 0 ]; then
	ShowSyntax
	exit 1
else
	CheckPermission
	ConfigureConnections
	service network-manager restart
fi
exit 0
