#!/bin/bash

CP=$(which cp)
CPom="$CP --no-preserve=mode,ownership"
MV=$(which mv)
WORK_DIR="/var/mikbill/mikbill_dhcp"
CURRENT_DIR=$(pwd)
mikbillDHCP_IP="0.0.0.0"
SERVICE=$(which service)
SYSTEMCTL=$(which systemctl)

RADDB="/etc/raddb"
RADNAME="radiusd"
if [[ ! -d "$RADDB" ]]
then
	RADDB="/etc/freeradius/3.0"
	RADNAME="freeradius"
	if [[ ! -d "$RADDB" ]]
	then
		RADDB="/etc/freeradius"
		RADNAME="freeradius"
		if [[ ! -d "$RADDB" ]]
		then
			echo "cant detect radius dir"
			exit 1
		fi
	fi
fi

function copy_files() {
	if [[ -f $WORK_DIR/mikbill.pl ]]
	then
		$CP $WORK_DIR/mikbill.pl $RADDB/mikbill.pl
		$CP $WORK_DIR/linelog $RADDB/modules/linelog
		$CP $WORK_DIR/dhcp $RADDB/sites-enabled/dhcp
	else
		echo "mikbill dhcp files not found"
		exit 1
	fi
}

function append_ipaddress() {
	sed -i "s|IPSERVER|$mikbillDHCP_IP|g" $RADDB/sites-enabled/dhcp
}

function do_restart() {
	if [[ ! -z "$SERVICE" ]]
	then
		$SERVICE $RADNAME restart
	fi

	if [[ ! -z "$SYSTEMCTL" ]]
	then
		$SYSTEMCTL restart $RADNAME 
	fi
}

INDEX=1
IPADDRESSES=$(ip -o addr | awk '!/^[0-9]*: ?lo|link\/ether/ {gsub("/", " "); print $4}')
declare -A mikbillDHCP
for IPADDRESS in ${IPADDRESSES[*]}
do
  	echo "$INDEX) $IPADDRESS"
        mikbillDHCP[$INDEX]="$IPADDRESS"
        INDEX=$(expr $INDEX + 1)
done

read -r -p "Select IP address should use for Mikbill DHCP: " response
if [[ ${mikbillDHCP[$response]+abc} ]]
then
    mikbillDHCP_IP="${mikbillDHCP[$response]}"
    copy_files
    append_ipaddress
    do_restart
else
    echo "wrong answer"
    exit 0
fi

