#!/bin/sh

#  Description:
#
# natfree client tool to configure /etc/hosts with server configuration
# The default values of the parameters are obtained sourcing the files
# (with extension .cfg) from the /etc/natfree-d directory
#


###############
# global vars #
###############
# hosts file to write 
HOSTS_BASE_FILE="natfree-client"
DEBUG=""
ACTION=""

# Testing .... HOSTS_FILE="/tmp/arithmetic-server.hosts"

# load common functions
. /usr/share/natfree-common/natfree-common

CLIENT_IFACE="$(get_client_iface)"
IP_NUMBER="$(get_ip_number)"
# List of servers aliases to write (comma separated)
# TODO: revise list ...
SRV_ALIASES="$(get_srv_aliases)"
SRV_CIDR="$(get_srv_net)"
CLIENT_MODE="$(get_client_mode)"
SRV_ADDRESS="$(get_srv_addr)"

usage(){
        die "Usage" "$(basename "$0") [ OPTIONS ] COMMAND"  \
            "       OPTIONS:" \
	    "           -p NUMBER       : IP number/position in subnet (defults to $IP_NUMBER)" \
	    "           -a ALIASES_LIST : comma separated list of names (defaults to $SRV_ALIASES)" \
            "           -d              : debug mode (verbose)" \
	    "           -m MODE [PARAM] : MODE to use (defaults to $CLIENT_MODE):" \
	    "              -m i[nterface] [PHYS_IFACE] : get network addres from physical interface" \
	    "                                            and use IP arithmetic. (defaults to $CLIENT_IFACE)" \
	    "              -m n[etwork] [SRV_NETWORK]  : use provided CIDR (IP/MASK) to determine server network" \
	    "                                            and use IP arithmetic. (defaults to $SRV_CIDR)" \
	    "              -m f[ixed]   [FIXED_ADDRESS]: use provided IP for server address, no arithmetic." \
	    "                                            (defaults to $SRV_ADDRESS)" \
	    "              -m d[hcp]                   : use dhcp to determine server network and use IP arithmetic" \
	    "              -m a[uto]                   : auto try set config firstly by dhcp, if this fail set config " \
	    "						 from default interface with internet connection"\
            "       COMMAND:" \
            "           CONFIGURE|SET|UPDATE : update /etc/hosts file" \
            "           DESTROY|DELETE       : remove data from /etc/hosts file" \
            "Command and mode names can be used in lower or upper case and abbreviated down to a single letter." \
            "Where there is ambiguity, dictionary order is used to select a command."
}

#############
# functions #
#############
main(){
        # check parameters

        [ "$1" ] || usage
        OPTIONS=""
        while echo "x$1" | grep -q "^x-" ; do
                OPTIONS="$OPTIONS $1"
                case "$1" in
			-a)
                                [ "$#" -ge 3 ] || usage
                                shift
				SRV_ALIASES="$(get_srv_aliases "$1")"
				;;
			-p)
                                [ "$#" -ge 3 ] || usage
                                shift
				IP_NUMBER="$(get_ip_number "$1")"
				;;
			-f)	
                                [ "$#" -ge 3 ] || usage
                                shift
				SRV_ADDRESS="$(get_srv_addr "$1")"
				;;
			-m)	
                                [ "$#" -ge 3 ] || usage
                                shift
				CLIENT_MODE="$(get_client_mode "$1")"
                		case "$CLIENT_MODE" in
                        		i*)
						OPTION="interface"
						echo "$OPTION" |grep -q "^$CLIENT_MODE" || usage
                                		if [ "$2" ] ; then
                                			CLIENT_IFACE="$(get_client_iface "$2")"
                                			shift
						fi
                                		;;
					n*)	
						OPTION="network"
						echo "$OPTION" |grep -q "^$CLIENT_MODE" || usage
                                		if [ "$2" ] ; then
							SRV_CIDR="$(get_srv_net "$2")"
                                			shift
						fi
						;;
					f*)	
						OPTION="force"
						echo "$OPTION" |grep -q "^$CLIENT_MODE" || usage
                                		if [ "$2" ] ; then
							SRV_ADDRESS="$(get_srv_addr "$2")"
                                			shift
						fi
						;;
					d*)	
						OPTION="dhcp"
						echo "$OPTION" | grep -q "^$CLIENT_MODE" || usage
						;;
					a*)
						OPTION="auto"
						echo "$OPTION" | grep -q "^CLIENT_MODE" || usage
						;;
					*)
						usage
						;;


				esac

				;;

                        -d)
                                DEBUG="Y"
                                ;;
                        *)
                                usage
                                ;;
                esac
                shift
        done
        [ "$1" ] || usage

        if [ "$DEBUG" ] ; then
                cat << EOF
- Options selected  : [$OPTIONS ]
- Physical interface: [ $CLIENT_IFACE ]
- IP number         : [ $IP_NUMBER ]
- Server IP         : [ $SRV_ADDRESS ]
- Server aliases    : [ $SRV_ALIASES ]
- Server network    : [ $SRV_CIDR ]
- Client mode       : [ $CLIENT_MODE ]
EOF
        fi

        A="$(echo "$1" |tr "[:lower:]" "[:upper:]")"

        case "$A" in
                D*)
			ACTION="DESTROY DELETE"
			OK=""
			for a in $ACTION ; do
				if echo "$a" |grep -q "^$A" ; then
				       OK="Y"
				fi
			done
			[ "$OK" ] || usage
                        [ -z "$DEBUG" ] || echo "- Action: [ $ACTION ]"
			delete_hosts_file "$HOSTS_BASE_FILE"
			update-hosts
			;;
		C*|S*|U*)
			ACTION="CONFIGURE SET UPDATE"
			OK=""
			for a in $ACTION ; do
				if echo "$a" |grep -q "^$A" ; then
				       OK="Y"
				fi
			done
			[ "$OK" ] || usage
                        [ -z "$DEBUG" ] || echo "- Action: [ $ACTION ]"

			# recopile necessary data
			# get DNS search domain from resolv.conf (if any)
			SEARCH_DOMAIN="$(get_domain)"
			[ -z "$SEARCH_DOMAIN" ] || SEARCH_DOMAIN=":${SEARCH_DOMAIN}"

			case "$CLIENT_MODE" in
				a*)
					# Get values from DHCP
					CIDR=$(n4d-vars getvalues LLIUREX_VLAN | cut -d "=" -f 2 | tail -c +2 | head -c -2)
					# 
					if [ "x$CIDR" = "x" ]; then
						CIDR="$(get_iface_cidr "$CLIENT_IFACE")"
					fi
					N_CART=$(n4d-vars getvalues CONTROLLED_CLASSROOM | cut -d "=" -f 2 | tail -c +2 | head -c -2)
					if [ -z "$N_CART" ]; then
						N_CART="1"
					fi
					SRV_IP="$(get_srv_cart_ip "$CIDR" "$N_CART" "$IP_NUMBER")"
					;;
				i*|d*)
					if [ `expr $CLIENT_MODE : '^d.*'` -gt 0 ]; then
						CIDR=$(n4d-vars getvalues LLIUREX_VLAN | cut -d "=" -f 2 | tail -c +2 | head -c -2)
					else
						CIDR="$(get_iface_cidr "$CLIENT_IFACE")"
					fi
					# get ip/mask in CIDR notation
					[ "$CIDR" ] || die "Unable to retrieve IP address from $CLIENT_MODE"
					# get IP_NUMBER available ip in subnet
					SRV_IP="$(get_srv_ip "$CIDR" "$IP_NUMBER")"
					;;
				n*)
					# use provided SRV_CIDR
	                                CIDR="$(get_srv_net "$SRV_CIDR")"
					[ "$CIDR" ] || die "Invalid CIDR value"
					# get IP_NUMBER available ip in subnet
					SRV_IP="$(get_srv_ip "$CIDR" "$IP_NUMBER")"
					;;
				f*)
					SRV_IP="$(get_srv_addr "$SRV_ADDRESS")"
					;;
			esac

			[ "$SRV_IP" ] || die "Invalid server IP"
                        [ -z "$DEBUG" ] || echo "  -- Server IP: [ $SRV_IP ]"

		        # generate .hosts file
			write_hosts_file "$HOSTS_BASE_FILE" "${SRV_IP}:${SRV_ALIASES}${SEARCH_DOMAIN}"

		        # update /etc/hosts
		        update-hosts
			;;
		*)
			usage
			;;
        esac

}

################
# main program #
################
main "$@"
exit 0

