#!/bin/bash
## TEST ####### MERGED CON INAIL
export MULTIPLE=`pidof configure_net | wc -w`
if [ "$MULTIPLE" -gt "2" ]  ; then
   echo "configure_net already running"
   exit 255
fi

export CONFIGURE_VERSION="2.5.2"
ETH_ENABLED=false
ETH_MODE=static
ETH_IP=192.168.3.1
ETH_MASK=255.255.255.0
ETH_GW=192.168.3.1
ETH_DNS1=10.0.1.51
ETH_DNS2=10.0.2.9

ETH_ENABLED=true
ETH_MODE=dhcp
ETH_IP=
ETH_MASK=
ETH_GW=
ETH_DNS1=
ETH_DNS2=

###
WIFI_ENABLED=true
WIFI_MODE=dhcp
WIFI_SSID=HTC9MG
WIFI_PASS=baccabacca
WIFI_IP=
WIFI_MASK=
WIFI_GW=
WIFI_DNS1=
WIFI_DNS2=

NET_NTP=pool.ntp.org
NET_ZONE=Europe/Paris

### ESERCIZIO #########################

#
# json exctract value di param
#
function json_param {
    picurl=`jsonpar.py -p $1 -f $CONFIG_NET`
}


function loadJson {
    log "Loading config..."
    json_param 'eth_enabled'  ; ETH_ENABLED="$picurl"  ; export ETH_ENABLED
    json_param 'eth_mode'     ; ETH_MODE="$picurl"     ; export ETH_MODE
    json_param 'eth_ip'       ; ETH_IP="$picurl"       ; export ETH_IP
    json_param 'eth_mask'     ; ETH_MASK="$picurl"     ; export ETH_MASK
    json_param 'eth_gw'       ; ETH_GW="$picurl"       ; export ETH_GW
    json_param 'eth_dns1'     ; ETH_DNS1="$picurl"     ; export ETH_DNS1
    json_param 'eth_dns2'     ; ETH_DNS2="$picurl"     ; export ETH_DNS2

    json_param 'wifi_enabled' ; WIFI_ENABLED="$picurl" ; export WIFI_ENABLED
    json_param 'wifi_mode'    ; WIFI_MODE="$picurl"    ; export WIFI_MODE
    json_param 'wifi_ssid'    ; WIFI_SSID="$picurl"    ; export WIFI_SSID
    json_param 'wifi_pass'    ; WIFI_PASS="$picurl"    ; export WIFI_PASS
    json_param 'wifi_ip'      ; WIFI_IP="$picurl"      ; export WIFI_IP

    json_param 'wifi_type'        ; WIFI_TYPE="$picurl"        ; export WIFI_TYPE
    json_param 'wifi_eap_pass'    ; WIFI_EAP_PASS="$picurl"    ; export WIFI_EAP_PASS
    json_param 'wifi_eap_user'    ; WIFI_EAP_USER="$picurl"    ; export WIFI_EAP_USER
    json_param 'wifi_hidden'      ; WIFI_HIDDEN="$picurl"      ; export WIFI_HIDDEN

    if [[ $WIFI_EAP_PASS == *"no par"* ]]; then
        log "no wifi_eap_pass, set to \"\" ($WIFI_EAP_PASS)"
        WIFI_EAP_PASS=""
    fi

    if [[ $WIFI_EAP_USER == *"no par"* ]]; then
        log "no wifi_eap_user, set to \"\" ($WIFI_EAP_USER)"
        WIFI_EAP_USER=""
    fi

    if [[ $WIFI_TYPE == *"no par"* ]]; then
        log "no wifi_type, set to \"\"     ($WIFI_TYPE)"
        WIFI_TYPE=""
    fi

    if [[ $WIFI_HIDDEN == *"no par"* ]]; then
        log "no wifi_hidden, set to \"\"   ($WIFI_HIDDEN)"
        WIFI_HIDDEN=""
    fi

    json_param 'wifi_mask'    ; WIFI_MASK="$picurl"    ; export WIFI_MASK
    json_param 'wifi_gw'      ; WIFI_GW="$picurl"      ; export WIFI_GW
    json_param 'wifi_dns1'    ; WIFI_DNS1="$picurl"    ; export WIFI_DNS1
    json_param 'wifi_dns2'    ; WIFI_DNS2="$picurl"    ; export WIFI_DNS2

    json_param 'net_ntp'      ; NET_NTP="$picurl"      ; export NET_NTP
    json_param 'net_zone'     ; NET_ZONE="$picurl"     ; export NET_ZONE
    json_param 'net_ntp_forced' ; NET_NTP_FORCED="$picurl"   ; export NET_NTP_FORCED

    if [[ "$NET_NTP_FORCED"  == *"no par"* ]]; then
        NET_NTP_FORCED="false"
        log "no net_ntp_forced, set to \"\"   ($NET_NTP_FORCED)"
    fi

}



CONFIG_NET="/home/st/configured_cfg_net.json"
CONNMAN_DIR=/var/lib/connman
WPACONF=/etc/wpa_supplicant/wpa_supplicant.conf
NTPCONF=/etc/systemd/timesyncd.conf
LOGCONF=/home/st/config_net_log.log

export ETH_ENABLED ETH_MODE ETH_IP ETH_MASK ETH_GW ETH_DNS1 ETH_DNS2
export WIFI_ENABLED WIFI_MODE WIFI_SSID WIFI_PASS WIFI_IP WIFI_MASK WIFI_GW WIFI_DNS1 WIFI_DNS2
export NET_NTP NET_ZONE NTPCONF
export CONFIG_NET
export CONNMAND_DIR
export WPACONF

#CONFIG ETHERNET

function log () {
    echo `date +"%Y-%m-%d %T"` "$1" >>"$LOGCONF"
    echo `date +"%Y-%m-%d %T"` "$1"
}


function connmanforce () {
    export SERVICES_SEARCH_MAX=3
    export SERVICES_LOOP=0
    connmanstate
    systemctl start connman
    connmanstate
    connmanctl enable ethernet
    connmanctl enable wifi
    sleep 3
    while [ 1 ]
    do
    	export SERVICES_AVAILABLE=`connmanctl services | wc -l`
    	connmanctl services
    	log "(connmanforce) connman services available : $SERVICES_AVAILABLE"
    	export SERVICES_ERROR=`echo $SERVICES_AVAILABLE | grep Error | wc -l`
    	if [ "$SERVICES_AVAILABLE" -gt 0  -o "$SERVICES_ERROR" -gt 0 ]
    	then
    		log "(connmanforce) connman services available, continue"
    		sleep 3
    		return 0
    	else
    		sleep 3
    		export SERVICES_LOOP=`expr $SERVICES_LOOP + 1`
    		log "(connmanforce) connman services NOT available : $SERVICES_AVAILABLE wait 1 sec ($SERVICES_LOOP/$SERVICE_SEARCH_MAX)"
    		if [ "$SERVICES_LOOP"  -gt "$SERVICES_SEARCH_MAX" ]
    		then
    			log "(connmanforce) connman services ERROR NOT available ($SERVICES_LOOP/$SERVICE_SEARCH_MAX)"
    			log "(connmanforce) connman services ERROR NOT available ($SERVICES_LOOP/$SERVICE_SEARCH_MAX)"
    			log "(connmanforce) connman services ERROR NOT available ($SERVICES_LOOP/$SERVICE_SEARCH_MAX)"
    			log "(connmanforce) connman services ERROR NOT available ($SERVICES_LOOP/$SERVICE_SEARCH_MAX)"
    			log "(connmanforce) connman services ERROR NOT available ($SERVICES_LOOP/$SERVICE_SEARCH_MAX)"
    			log "(connmanforce) connman services ERROR NOT available ($SERVICES_LOOP/$SERVICE_SEARCH_MAX)"
    			return 255
    		fi
    	fi
    done
    return 0        # never happens
}

function connmanstate () {
    export CONN=`systemctl is-active connman`
    case $CONN in
    active)
            log " (connmanstate) : active "
            return 0
            ;;
    inactive)
            log "(connmanstate) : inactive "
            return 1
            ;;
    *)
            log "(connmanstate) : unknown :$CONN"
            return 2
            ;;
    esac
}

function etherstate () {
    export CARRIER=`cat /sys/class/net/eth0/carrier 2>>/dev/null`
    if [ "$CARRIER" = "" ]
    then
            CARRIER="255"
    fi
    export STATE=`cat /sys/class/net/eth0/operstate`
    log "(etherstate) Link: $CARRIER State: $STATE"
    return $CARRIER
}


#
# config
#
function deleteconf () {
    log "deleteconf $1"
    if [ "$1" == "wifi" ]
    then
        rm -rf $CONNMAN_DIR/wifi*
    else
        rm -rf $CONNMAN_DIR/ethernet*
    fi
}

function appendNtp () {
    echo "$1" >>$NTPCONF.NEW
}

function createNtp () {
    # rm -rf $NTPCONF
if grep -i omantelpassy /home/st/cfg_dominio.json -q ; then OMAN=true ; else OMAN=false ; fi ; echo "Dominio su OMAN=$OMAN"
    if [ $WIFI_ENABLED == "true" ]
    then
        if [ $WIFI_MODE == "static" -o "$OMAN" == "true" -o "$NET_NTP_FORCED" = "true" ]
        then
	    appendNtp "[Time]"
	    appendNtp "Servers = $NET_NTP "
	    appendNtp " "
	else
	    appendNtp "[Time]"
	    appendNtp "# ###Servers = $NET_NTP "
	    appendNtp " "
	fi	
    else
	    if [ $ETH_ENABLED == "true" ]
	    then
		    if [ $ETH_MODE == "static" -o "$OMAN" == "true" -o "$NET_NTP_FORCED" = "true" ]
			then
			    appendNtp "[Time]"
			    appendNtp "Servers = $NET_NTP "
			    appendNtp " "
			else
			    appendNtp "[Time]"
			    appendNtp "# ###Servers = $NET_NTP "
			    appendNtp " "
			fi
	    else
		log "NTP Conf error eth/wifi "
	    fi
    fi

    diff $NTPCONF $NTPCONF.NEW >>/dev/null
    RC=$?
    export RC
    if [ "$RC" == "0" -a "$OMAN" != "true" -a "$NET_NTP_FORCED" != "true" ]
    then
        log "NTP Conf not changed "
        rm $NTPCONF.NEW
    else
        log "NTP Conf changed or forced,Restarted systemd-timesyncd service "
        cp $NTPCONF.NEW $NTPCONF
        rm $NTPCONF.NEW
        systemctl restart systemd-timesyncd
    fi
}

function appendConfig () {
    echo "$1" >>"$CONFIG_TMP"
    # echo "$1" >>/var/lib/connman/$SERVICE-psk.config
}

function appendConfigLast () {
	if [ $WIFI_ENABLED == "true" ]
    then
        if [ $WIFI_MODE == "static" ]
    	then
        	appendConfig "Nameservers=$WIFI_DNS1,$WIFI_DNS2 "
            appendConfig "Timeservers=$NET_NTP "        
        else 
            log "Enabled Ethernet with DHCP, ignored Nameservers and Timeserver"
        fi
	fi
	if [ $ETH_ENABLED == "true" ]
    then
        if [ $ETH_MODE == "static" ]
    	then
        	appendConfig "Nameservers=$ETH_DNS1,$ETH_DNS2 "
            appendConfig "Timeservers=$NET_NTP "
        else
            log "Enabled Wifi with DHCP, ignored Nameservers and Timeserver"
        fi
	fi

    ## cat /var/lib/connman/$SERVICE-psk.config
    ## echo "Created /var/lib/connman/$SERVICE-psk.config "
    log "Created $SERVICE-psk.config config"
}

function appendConfigExecute () {
    log "copy $CONFIG_TMP to $CONFIG_EXECUTE"
    cp "$CONFIG_TMP" "$CONFIG_EXECUTE"
}

function createConfig () {
    log "delete file: /var/lib/connman/$SERVICE-psk.config "
    rm -rf /var/lib/connman/$SERVICE-psk.config
    export CONFIG_TMP="/tmp/$PPID"
    log "delete file: $CONFIG_TMP "
    rm "$CONFIG_TMP"

    if [ "$WIFI_ENABLED" == "true" -a "$WIFI_HIDDEN" == "true" ]
    then
        export SERVICE="$HIDDEN_NET"
    fi

    export CONFIG_EXECUTE="/var/lib/connman/$SERVICE-psk.config"
    log "tmp file:$CONFIG_TMP, dest file:$CONFIG_EXECUTE"

	if [ $WIFI_ENABLED == "true" ]
    then
	    appendConfig "[global]"
	    appendConfig "Name = RC"
	    appendConfig "Description = RC Wifi service config file"
	    appendConfig " "
	    appendConfig "[service_$SERVICE]"
    	appendConfig "Type=wifi"
    	appendConfig "Name=$WIFI_SSID"    
	    if [ "$WIFI_HIDDEN" == "true" ]
	    then
	        log "set wifi_hidden = true"
	        appendConfig "Hidden=true"
	    fi

	    if [ "$WIFI_TYPE" == "" -o "$WIFI_TYPE" == "WPA2-PSK" ]
	    then
	        log "no wifi_type, using default wpa2"
	        appendConfig "Passphrase=$WIFI_PASS"
	    fi

	    if [ "$WIFI_TYPE" == "WPA2 EAP-PSK" ]
	    then
	        log "wifi_type WPA2 EAP-PSK, using Passphrase of wpa2"
	        appendConfig "EAP=peap"
	        appendConfig "Phase2=MSCHAPV2"
	        appendConfig "Identity=$WIFI_EAP_USER"
	        appendConfig "Passphrase=$WIFI_EAP_PASS"
	    fi
    fi

	if [ $ETH_ENABLED == "true" ]
	then
	    appendConfig "[global]"
	    appendConfig "Name = RC"
	    appendConfig "Description = RC ethernet service config file"
	    appendConfig " "
	    appendConfig "[service_$SERVICE]"
    	appendConfig "Type=ethernet"
    fi

    appendConfig "IPv6=off"
    ## appendConfig "AutoConnect = true "
}



################## MAIN

log "configure_net started v. $CONFIGURE_VERSION"
if [ "$1" != "" ]
then
    log "$0 try_only_mode"
    TRY_ONLY_MODE="true" ; export TRY_ONLY_MODE
else
    TRY_ONLY_MODE="false" ; export TRY_ONLY_MODE
fi

loadJson

if [ $ETH_ENABLED == "true" ]
then
    if ! connmanforce
    then
        log "Error in verify connman, exit"
        exit  254                              ## 23/4/2020 COVID
    fi
    log "Configuring ethernet..."
    log "disabling wifi..."
    connmanctl disable wifi
    log "enable ethernet"                ### 26/6
    connmanctl enable ethernet           ### 26/6

    if [ "$TRY_ONLY_MODE" == "true" ]
    then
        log "try only disabling(5s), enabling(5s) ..."

        log "connmanctl ethernet, sleep 5"
        connmanctl disable ethernet
        sleep 5

        log "connmanctl enable ethernet, sleep 5"
        connmanctl enable ethernet
        sleep 5

    else
        log "configure : stopped, deleting, started, configure, enabling..."


        log "configure: control if services available"
        SERVICE=`connmanctl services | grep ethernet | awk '{ print $NF }'`
        export SERVICE

        if [ x$SERVICE == x ]
        then
            log "configure: WARNING !!! No ethernet service present"
            export SERVICE="FINTO"

            etherstate
        else
            log "configure: Ethernet service present : $SERVICE, continue configure"


            log "systemctl stop connman, sleep 5"
            systemctl stop connman
            sleep 5

            log "deleting old ethernet configuration..."
            deleteconf ethernet

            log "systemctl start connman, sleep 10"
            systemctl start connman
            sleep 10

            SERVICE=`connmanctl services | grep ethernet | awk '{ print $NF }'`
            export SERVICE

            log "systemctl stop connman, sleep 5 to build $SERVICE"
            systemctl stop connman
            sleep 5

            if [ x$SERVICE == x ]
            then
                log "No ethernet service present"
                export SERVICE="FINTO"
            else
                log "Ethernet service : $SERVICE"
    	        createConfig        
                case "$ETH_MODE" in
                    static)
            		    # modifiche per pi che perde dopo il boot
            		    ###################################
                        # connmanctl config $SERVICE --ipv4 manual $ETH_IP $ETH_MASK $ETH_GW --nameservers $ETH_DNS1 $ETH_DNS2 --timeservers $NET_NTP --ipv6 off
                        # log "Ethernet configured STATIC ip:$ETH_IP mask:$ETH_MASK gw:$ETH_GW dns:$ETH_DNS1,$ETH_DNS2 ntp:$NET_NTP"
                        # log "connmanctl config $SERVICE --autoconnect yes --ipv6 off"
                        # connmanctl config $SERVICE --autoconnect yes --ipv6 off
                        # log "connmanctl connect $SERVICE"
                        # connmanctl connect $SERVICE
            		    # log "`connmanctl services $SERVICE`"
            		    ##############################

                        log "Ethernet static conf :  $ETH_IP/$ETH_MASK/$ETH_GW "
                        # connmanctl agent on
                        # connmanctl config $SERVICE --ipv4 manual $WIFI_IP $WIFI_MASK $WIFI_GW --nameservers $WIFI_DNS1 $WIFI_DNS2 --timeservers $NET_NTP
                        # connmanctl scan wifi
                        appendConfig "IPv4=$ETH_IP/$ETH_MASK/$ETH_GW"
                        appendConfigLast
                        appendConfigExecute

            		    log "systemctl start connman, sleep 5 to activate $SERVICE"
            		    systemctl start connman
            		    sleep 10

          	            connmanctl services >>/dev/null

                        log "connmanctl config $SERVICE --autoconnect yes "
                        connmanctl config $SERVICE --autoconnect yes
                        log "connmanctl connect $SERVICE"
                        connmanctl connect $SERVICE
            		    log "`connmanctl services $SERVICE`"
                    ;;

                    dhcp)
            		    # per pi
            		    #############################
                        connmanctl config $SERVICE --ipv4 dhcp --timeservers $NET_NTP --ipv6 off
                        log "Ethernet configured DHCP ntp:$NET_NTP"
                        log "connmanctl config $SERVICE --autoconnect yes --ipv6 off"
                        connmanctl config $SERVICE --autoconnect yes
                        log "connmanctl connect $SERVICE"
                        connmanctl connect $SERVICE
            		    log "`connmanctl services $SERVICE`"
            		    #############################
                        log "Ethernet dhcp conf "
                        # connmanctl scan wifi
                        # append DHCP to file
                        appendConfig "IPv4=dhcp"
                        appendConfigLast
            		    appendConfigExecute

            		    log "systemctl start connman, sleep 10 to activate $SERVICE"
            		    systemctl start connman
            		    sleep 10

          	            connmanctl services >>/dev/null

                        log "connmanctl config $SERVICE --autoconnect yes "
                        connmanctl config $SERVICE --autoconnect yes
                        log "connmanctl connect $SERVICE"
                        connmanctl connect $SERVICE
            		    log "`connmanctl services $SERVICE`"

                    ;;
                    *)
                        log "Ethernet Mode unknown : $ETH_MODE"
                esac
            fi
        fi



    fi
else
    log "Ethernet deconfigured "
fi

# CONFIG WIFI
if [ $WIFI_ENABLED == "true" ]
then
    if ! connmanforce
    then
        log "Error in verify connman, exit"
        exit 255                              ## 23/4/2020 COVID
    fi
    log "Configuring WIFI $WIFI_SSID..."
    log "disabling ethernet..."
    connmanctl disable ethernet
    log "enable wifi"                ### 26/6
    connmanctl enable wifi           ### 26/6
    connmanctl scan wifi             ### 26/6
    connmanctl scan wifi             ### 26/6

    if [ "$TRY_ONLY_MODE" == "true" ]
    then
        log "try_only : disabling(5s), enabling(5s), scanning(15s)..."

        log "connmanctl disable wifi, sleep 5"
        connmanctl disable wifi
        sleep 5

        log "connmanctl enable wifi, sleep 5"
        connmanctl enable wifi
        sleep 5

        log "connmanctl scan wifi, sleep 15"
        connmanctl scan wifi
        connmanctl scan wifi
        sleep 15
    else
        log "configure : disabling, enabling, scanning..."

        log "systemctl stop connman, sleep 5"
        systemctl stop connman
        sleep 5

        log "deleting old wifi configuration..."
        deleteconf wifi

        log "systemctl start connman, sleep 10"
        systemctl start connman
        sleep 10

        log "connmanctl enable wifi, sleep 5"
        connmanctl enable wifi
        sleep 5

        log "connmanctl scan wifi, sleep 15"
        connmanctl scan wifi
        connmanctl scan wifi
        sleep 15

        log "found networks : "
        WI=`connmanctl services` ; export WI
        log "$WI"

        SERVICE=`connmanctl services | grep wifi | grep " $WIFI_SSID " |  awk '{ print $NF }'`
        export SERVICE

        export HIDDEN_NET=`connmanctl services | grep hidden | head -1 | awk '{ print $1 }'`
        if [ "$HIDDEN_NET" = "" -a "$WIFI_HIDDEN" == "true" ]
        then
            log "ATTENTION : param wifi_hidden = true and NO_HIDDEN_NETWORK FOUND !!!!"
            export HIDDEN_NET="no_hidden_network_found"
        fi

        if [ x$SERVICE == x -a "$WIFI_HIDDEN" == "true" ]
        then
            ###log "Hidden network : SERVICE set \"wifi_$WIFI_SSID\" "
            ###SERVICE="wifi_$WIFI_SSID"
            ###export SERVICE
            log "Hidden network : SERVICE set \"$HIDDEN_NET\" "
        fi

        if [ x$SERVICE == x -a "$WIFI_HIDDEN" != "true" ]
        then
            log "No wifi service \"$WIFI_SSID\" present"
        else
            log "Wifi service : $SERVICE"
            createConfig

            case "$WIFI_MODE" in
                static)
                    log "Wifi static conf :  $WIFI_IP/$WIFI_MASK/$WIFI_GW "
                    # connmanctl agent on
                    # connmanctl config $SERVICE --ipv4 manual $WIFI_IP $WIFI_MASK $WIFI_GW --nameservers $WIFI_DNS1 $WIFI_DNS2 --timeservers $NET_NTP
                    # connmanctl scan wifi
                    appendConfig "IPv4=$WIFI_IP/$WIFI_MASK/$WIFI_GW"
                    appendConfigLast
                    appendConfigExecute
                    connmanctl services >>/dev/null

                    log "connmanctl config $SERVICE --autoconnect yes "
                    connmanctl config $SERVICE --autoconnect yes
                    log "connmanctl connect $SERVICE"
                    connmanctl connect $SERVICE
                    log "`connmanctl services $SERVICE`"
                ;;

                dhcp)
                    log "Wifi dhcp conf "
                    # connmanctl scan wifi
                    # append DHCP to file
                    appendConfig "IPv4=dhcp"
                    appendConfigLast
                    appendConfigExecute
                    connmanctl services >>/dev/null

                    log "connmanctl config $SERVICE --autoconnect yes "
                    connmanctl config $SERVICE --autoconnect yes
                    log "connmanctl connect $SERVICE"
                    connmanctl connect $SERVICE
                    log "`connmanctl services $SERVICE`"
                ;;

                *)
                    log "WIFI Mode unknown : $WIFI_MODE"
            esac
            log "Wifi configured : $WIFI_SSID"
        fi
        connmanctl scan wifi
        connmanctl scan wifi
    fi
else
    log "WIFI deconfigured"
fi

##### Timezone

createNtp
rm /etc/localtime
ln -s /usr/share/zoneinfo/$NET_ZONE /etc/localtime
log "Zoneinfo created"

log "Net configured"
log "configure_net ended v. $CONFIGURE_VERSION"
exit 0
