#!/bin/bash
#
#       Copyright (C) MOXA Inc. All rights reserved.
#       Copyright (C) 2014-2015  Lock Lin <Lock.Lin@moxa.com>
#       Copyright (C) 2015       Harry YJ Jhou <HarryYJ.Jhou@moxa.com>
#
#       This software is distributed under the terms of the
#       MOXA License.  See the file COPYING-MOXA for details.
#
#       cell_mgmt
#               cellular management. It supports sierra MC9090 MC7304 MC7354.
#
 

#--------- initial Global variable ---------
VERSION="1.7 V2426A 15050518"
SCRIPTNAME=$(basename $0)
LOCK_DIR="/var/lock/${SCRIPTNAME}"

#PORT
GPS_PORT="/dev/ttyUSB1"
CELL_PORT="/dev/ttyUSB2"
QMI_PORT="/dev/cdc-wdm0"
QMI_NODE="wwan0"

#QMI
#new libqmi includes a tool called "qmi-proxy"
#use qmicli -p means interaction with the QMI interface of modem by "qmi-proxy"
QMICLI="/usr/bin/qmicli -p"
QMI_PROXY="/usr/local/libexec/qmi-proxy"

#carriers ( for usage )
CARRIER="Verizon|ATT|Sprint|Generic"

# config file of cell_mgmt
CELL_MGMT_PROFILE=/etc/cell_mgmt.conf

# get cellular model information
id=`cat /sys/bus/usb/devices/1-1/product 2>/dev/null`
# Sierra MC73x4
# MC7354 & MC7304 we need to modify QMI PORT NODE & GPS PORT
if [ x"$id" == x"MC7354" ] || [ x"$id" == x"MC7304" ]; then
	QMI_PORT="/dev/cdc-wdm1"
	QMI_NODE="wwan1"
	GPS_PORT="/dev/ttyUSB0"
	CELL_PORT="/dev/ttyUSB1"
fi


#for qmi-network variable
#qmi-network 1.12.6
DEVICE=$QMI_PORT
#COMMAND=$2
#load interface config
if [ -f $CELL_MGMT_PROFILE ]; then
	. $CELL_MGMT_PROFILE
fi
if [ x"$INTERFACE" == x"" ]; then
	INTERFACE=0
fi

#set profile
if [ x"$INTERFACE" == x"" -o x"$INTERFACE" == x"0" ]; then
        STATE_FILE=/tmp/qmi-network-state
        PROFILE_FILE=/etc/qmi-network.conf
else
        STATE_FILE=/tmp/qmi-network-state$INTERFACE
        PROFILE_FILE=/etc/qmi-network.conf$INTERFACE
fi

# for V2400LX
DEVICE_DIR="/sys/devices/pci0000:00/0000:00:1a.0/usb1/1-1/"
DEVICE_SLOT_DIR=( 1-1.3/1-1.3.1/1-1.3.1:1.4
                  1-1.3/1-1.3.2/1-1.3.2:1.4
                  1-1.4/1-1.4.1/1-1.4.1:1.4
                  1-1.4/1-1.4.2/1-1.4.2:1.4 )

if [ $(kversion | awk '{print $1}') == "V2400A-LX" ]; then
	
        QMI_NODE="wwan${INTERFACE}"
        
        for (( i=0 ; i<4 ; i++ ))
        do
                ELEMENT="${DEVICE_SLOT_DIR[$i]}"
                if [ -d "${DEVICE_DIR}${ELEMENT}/net/" ]; then
                        if [ x"$(ls ${DEVICE_DIR}${ELEMENT}/net/)" == x"$QMI_NODE" ]; then
                                QMI_PORT="/dev/$(ls ${DEVICE_DIR}${ELEMENT}/usbmisc/)"
                                let SLOT=$i+1
                                let CELL_PORT=$i*4+2
                                CELL_PORT=/dev/ttyUSB$CELL_PORT
                                break
                        fi
                fi
        done
	DEVICE=$QMI_PORT
        
fi
#--------- initial Global variable ---------

#--------- qmi-network functions -----------
load_profile ()
{
    if [ -f $PROFILE_FILE ]; then
        # Loading profile
        . $PROFILE_FILE
    fi
}

save_state ()
{
    KEY=$1
    VAL=$2

    echo "Saving state... ($KEY: $VAL)"

    if [ -f $STATE_FILE ]; then
        PREVIOUS=`cat $STATE_FILE`
        PREVIOUS=`echo "$PREVIOUS" | grep -v $KEY`
        if [ "x$PREVIOUS" != "x" ]; then
            echo $PREVIOUS > $STATE_FILE
        else
            rm $STATE_FILE
        fi
    fi

    if [ "x$VAL" != "x" ]; then
        echo "$KEY=\"$VAL\"" >> $STATE_FILE
    fi
}

load_state ()
{
    if [ -f $STATE_FILE ]; then
        #Loading previous state
        . $STATE_FILE
    fi
}

clear_state ()
{
    echo "Clearing state..."
    rm -f $STATE_FILE
}

start_network ()
{
    if [ "x$CID" != "x" ]; then
        USE_PREVIOUS_CID="--client-cid=$CID"
    fi

    if [ "x$PDH" != "x" ]; then
        echo "error: cannot re-start network, PDH already exists" 1>&2
        exit 3
    fi

    START_NETWORK_CMD="qmicli -p -d $DEVICE --wds-start-network=$APN $USE_PREVIOUS_CID --client-no-release-cid"
    echo "Starting network with '$START_NETWORK_CMD'..."

    if [ "x$QMIDEBUG" != "x" ]; then
        if [ x"$INTERFACE" == x"" -o x"$INTERFACE" == x"1" ]; then
        START_NETWORK_OUT="\
[/dev/cdc-wdm0] Network started
        Packet data handle: '3634026241'
[/dev/cdc-wdm0] Client ID not released:
        Service: 'wds'
        CID: '80'"
        else
        START_NETWORK_OUT="\
[/dev/cdc-wdm1] Network started
        Packet data handle: '363402624$3'
[/dev/cdc-wdm1] Client ID not released:
        Service: 'wds'
        CID: '80'"
        fi
    else
        START_NETWORK_OUT=`$START_NETWORK_CMD`
    fi

    # Save the new CID if we didn't use any before
    if [ "x$CID" = "x" ]; then
        CID=`echo "$START_NETWORK_OUT" | sed -n "s/.*CID.*'\(.*\)'.*/\1/p"`
        if [ "x$CID" = "x" ]; then
            echo "error: network start failed, client not allocated" 1>&2
            exit 1
        else
            save_state "CID" $CID
        fi
    fi

    PDH=`echo "$START_NETWORK_OUT" | sed -n "s/.*handle.*'\(.*\)'.*/\1/p"`
    if [ "x$PDH" = "x" ]; then
        echo "error: network start failed, no packet data handle" 1>&2
        # Cleanup the client
        qmicli -p -d "$DEVICE" --wds-noop --client-cid="$CID"
        clear_state
        exit 2
    else
        save_state "PDH" $PDH
    fi

    echo "Network started successfully"
}

stop_network ()
{
    if [ "x$CID" = "x" ]; then
        echo "Network already stopped"
    elif [ "x$PDH" = "x" ]; then
        echo "Network already stopped; need to cleanup CID $CID"
        # Cleanup the client
        qmicli -p -d "$DEVICE" --wds-noop --client-cid="$CID"
    else
        STOP_NETWORK_CMD="qmicli -p -d $DEVICE --wds-stop-network=$PDH --client-cid=$CID"
        echo "Stopping network with '$STOP_NETWORK_CMD'..."

        if [ "x$QMIDEBUG" != "x" ]; then
            STOP_NETWORK_OUT="\
[/dev/cdc-wdm$INTERFACE] Network stopped
"
        else
            STOP_NETWORK_OUT=`$STOP_NETWORK_CMD`
        fi

        echo "Network stopped successfully"
    fi

    clear_state
}

packet_service_status ()
{
    if [ "x$CID" != "x" ]; then
        USE_PREVIOUS_CID="--client-cid=$CID --client-no-release-cid"
    fi

    STATUS_CMD="qmicli -p -d $DEVICE --wds-get-packet-service-status $USE_PREVIOUS_CID"
    echo "Getting status with '$STATUS_CMD'..."

    if [ "x$QMIDEBUG" != "x" ]; then
        STATUS_OUT="\
[/dev/cdc-wdm0] Connection status: 'disconnected'
"
    else
        STATUS_OUT=`$STATUS_CMD`
    fi

    CONN=`echo "$STATUS_OUT" | sed -n "s/.*Connection status:.*'\(.*\)'.*/\1/p"`
    if [ "x$CONN" = "x" ]; then
        echo "error: couldn't get packet service status" 1>&2
        exit 2
    else
        echo "Status: $CONN"
        if [ "x$CONN" != "xconnected" ]; then
            exit 64
        fi
    fi
}


# Load profile, if any
load_profile

# Load previous state, if any
load_state

#--------- qmi-network functions -----------


#check proxy status
chk_proxy_status () {
    proxy_status=`ps aux | grep -v "grep" | grep "qmi-proxy"`
    #if [ x"$proxy_status" == x"" ]; then
    if [ -z "$proxy_status" ]; then
        #running in the background
        ${QMI_PROXY} &
    fi
}

#check cellular status
cell_status () {
    #con_status=`qmi-network ${QMI_PORT} status | grep "Status"`
    con_status=$(packet_service_status | grep "Status")
    echo ${con_status}
    if [ x"$(echo ${con_status}| awk '{print $2}')" == x"connected" ]; then
        exit 0
    else
        exit 1
    fi
}

#cellular signal strength in dbm
cell_signal () {
        # check signal_dbm is a value or not
        local temp
        # check proxy status
        chk_proxy_status
        
        signal=`$QMICLI -d ${QMI_PORT} --nas-get-signal-strength | tr "'" " " | grep "Network" | head -1 | awk '{print $2 " " $4}'`
        signal_dbm="$(echo $signal | awk '{print $2}')"
	temp=$(echo $signal_dbm | bc 2>/dev/null )
	if [ x"$temp" != x"$signal_dbm" ] || [ x"" == x"$signal_dbm" ]; then
		echo "signal out of range" && return 1
	fi
	if [ "$signal_dbm" -le "-52" ] && [ "$signal_dbm" -ge "-110" ] ; then
                echo "${signal} dbm"
                return 0
        else
                echo "signal out of range"
                return 1
        fi
}

#cellular power on by GPIO
cell_power_on () {
        local SLOT
	if [ x"$(kversion | awk '{print $1}' )" == x"V2400A-LX"  ]; then
                if [ -f /etc/slot_cell.conf$INTERFACE ]; then
			SLOT="$(cat /etc/slot_cell.conf$INTERFACE )"
			mx-dkcontrol $SLOT 1
		else
			echo "error interface..."
                fi
        fi
}

#cellular power off by GPIO
cell_power_off () {
	if [ x"$(kversion | awk '{print $1}' )" == x"V2400A-LX"  ]; then
                echo $SLOT > /etc/slot_cell.conf$INTERFACE
                if [ x"$SLOT" == x"" ]; then                
			echo "error interface..."
			exit 1
		fi
                mx-dkcontrol $SLOT 0
        fi
}

#cellular start
cell_start () {

        # check proxy status
        chk_proxy_status
        	
	local pin_status
	local APN=""
	local Username=""
	local Password=""
	local PIN="" 
	
	# load configuration file
	if [ -e "$PROFILE_FILE" ]; then
		. $PROFILE_FILE
	else
		echo "warning : file $PROFILE_FILE does not exist."
	fi
        

	# Sierra MC73x4
	# if configuration file (/etc/qmi-network.conf) does not exist
	# the start function need 4 parameters( APN, Username, Password, PIN )
	if [ ! -e $PROFILE_FILE ]; then
		
		if [ $# -lt 1 ]; then
			echo "Usage: cell_mgmt \"start\" \
			[APN=[APN], Username=[username], Password=[password], PIN=[pin_code]]"
			echo "example:"
			echo "		cell_mgmt start APN=internet Username=user Password=pass PIN=0000"
		    exit 1
        else
			# write APN Username Password PIN_code to /etc/qmi-network.conf
			# users start cellular do not need to set APN Username Password PIN_code again	
			for args in $@
			do
				if [ "$(echo $args | grep "APN=")" ]; then
					APN="${args##*APN=}"
				elif [ "$(echo $args | grep "Username=")" ]; then
					Username="${args##*Username=}"
				elif [ "$(echo $args | grep "Password=")" ]; then
					Password="${args##*Password=}"
				elif [ "$(echo $args | grep "PIN=")" ]; then
					PIN="${args##*PIN=}"
				else
					echo "Unknown:$args"
				fi
			done

			echo "APN=$APN" >> $PROFILE_FILE
			echo "Username=$Username" >> $PROFILE_FILE
			echo "Password=$Password" >> $PROFILE_FILE
			echo "PIN=$PIN" >> $PROFILE_FILE
			# cellular start again
			cell_mgmt start
		fi
	
	else
		# modify APN Username Password PIN
		for args in $@
		do
			if [ "$(echo $args | grep "APN=")" ]; then
				APN="${args##*APN=}"
				sed -i "s/APN=.*/APN=$APN/" $PROFILE_FILE
			elif [ "$(echo $args | grep "Username=")" ]; then
				Username="${args##*Username=}"
				sed -i "s/Username=.*/Username=$Username/" $PROFILE_FILE
			elif [ "$(echo $args | grep "Password=")" ]; then
				Password="${args##*Password=}"
				sed -i "s/Password=.*/Password=$Password/" $PROFILE_FILE
			elif [ "$(echo $args | grep "PIN=")" ]; then
				PIN="${args##*PIN=}"
				sed -i "s/PIN=.*/PIN=$PIN/" $PROFILE_FILE
			else
				echo "Unknown:$args"
			fi
		done
		
		pin_status="$($QMICLI -d $QMI_PORT --dms-uim-get-pin-status | grep "Status" | head -n 1)"
		if [ "$(echo $pin_status | grep "disabled")" ]; then
			echo "There is no PIN code"
		elif [ "$(echo $pin_status | grep "enabled-verified" )" ]; then
			echo "PIN code:Verified"
		else
			echo "PIN code:Not Verified"
			# Veryfy
			$QMICLI -d $QMI_PORT --dms-uim-verify-pin=PIN,$PIN
			killall ${QMI_PROXY} 2>/dev/null
			echo "Please wait ..."
			sleep 10	
			cell_mgmt start
			exit	
		fi
        	cell_signal > /dev/null
	        if [ x"$?" == x"1" ] ; then
			echo "There is no signal."
			exit 1		
		fi
                start_network
		# query IP from DHCP Server
                dhclient ${QMI_NODE}
		
	fi
    exit 0
}

cell_pin_code_status () {

	pin_status="$($QMICLI -d $QMI_PORT --dms-uim-get-pin-status | grep "Status" | head -n 1)"
        if [ "$(echo $pin_status | grep "disabled")" ]; then
		echo "There is no PIN code" && exit 2
        elif [ "$(echo $pin_status | grep "enabled-verified" )" ]; then
		echo "PIN code:Verified" && exit 0
	else
		echo "PIN code:Not Verified" && exit 1 
	fi

}

# cellular stop
cell_stop () {
	# release IP by dhclient -r
	dhclient -r ${QMI_NODE}
	# cellular stop by qmi-network
	#qmi-network ${QMI_PORT} stop
	stop_network
}

# cellular restart
cell_restart () {
	
	# restart cellular (reconnect)
	cell_mgmt "stop"
	sleep 5
	#PDH=""
        cell_mgmt "start"
	
}

# cellular reset
cell_reset () {
        if [ x"$(kversion | awk '{print $1}' )" == x"V2400A-LX"  ]; then
                echo "power off"
                power_off
                sleep 5
                echo "power on"
                power_on
                sleep 5
                echo "Done!"
        else
        	# reset cellular (module)
        	echo -e -n "AT!RESET\r\n" > ${CELL_PORT}
                echo "Done!"
        fi
}


# cellular set to default
cell_set_to_default () {
	
	local choise
	
	printf "\E[0;31;40m"
	echo "WARNING:It will RESET module to factory default"	
	printf "\E[0m"
	read -p "Do you want to continune?(y/n):" choice

	
	# check module status 
	cell_check_module 2>/dev/null
	[ x"$?" != x"0" ] && exit
	
	if [ $choice = "y" ]; then
		# entercnd : Enable access to password-protected commands
		echo -e -n 'AT!entercnd="A710"' > ${CELL_PORT} &> /dev/null
		# set to default
		echo -e -n "AT!NVBACKUP=0" > ${CELL_PORT} &> /dev/null
		echo -e -n "AT!NVDEF" > ${CELL_PORT} &> /dev/null
		echo -e -n "AT!NVRESTORE=0" > ${CELL_PORT} &> /dev/null
		echo -e -n "AT!NVRESTORE=1" > ${CELL_PORT} &> /dev/null
		echo -e -n "AT!NVRESTORE=2" > ${CELL_PORT} &> /dev/null
		
        	if [ -e "$PROFILE_FILE" ]; then
        	    cell_restart	
        	else
        	    echo "warning : file $PROFILE_FILE does not exist."
        	    cell_stop
        	    sleep 5
        	    echo "you neet to set the config file by 'cell_mgmt start'."
        	fi
	fi
}



# cellular sim status
cell_sim_status () {
        
        # check proxy status
        chk_proxy_status

	# get uim state
	# error information
	local err
	# if cellular module doesn't exist
cat > /tmp/cell_sim_status_check.sh << EOF
rm /tmp/sim_status.log 2>/dev/null
	echo "" > $QMI_PORT 
EOF
	chmod +x /tmp/cell_sim_status_check.sh
 	/tmp/cell_sim_status_check.sh 2>/tmp/cell_sim_status.log
	err="$(cat /tmp/cell_sim_status.log)" && rm /tmp/cell_sim_status_check.sh && rm /tmp/cell_sim_status.log
	
	qmi_info="$(echo $err | grep "No such device")"
		
	[ x"$qmi_info" != x"" ] && echo "Please insert the cellular module and reboot." && exit 1
	
	sim_info="$(eval $QMICLI -d ${QMI_PORT} --dms-uim-get-state 2> /tmp/sim_error_log)"
	
	if [ x"$(echo $sim_info | grep 'not-present' )" != x"" ]; then
		echo "Please insert the sim card and reboot." && exit 1
	elif [ x"$(cat /tmp/sim_error_log | grep 'error' )" != x"" ]; then
		# couldn't create QmiDevice
		echo "Please insert the cellular module and reboot." && exit 1
	else
		echo "$sim_info"
	fi
	rm /tmp/sim_error_log 2>/dev/null
    exit 0
}


# set pin code
cell_set_pin () {

        # check proxy status
        chk_proxy_status

	local pin_code="$1"
	[ -z $pin_code ] && echo "Usage: cell_mgmt set_pin [pin_code]" && exit 1
	if [ -e $PROFILE_FILE ]; then
		echo "old PIN=$PIN, new PIN=$pin_code"
		sed -i "s/PIN=.*/PIN=$pin_code/" $PROFILE_FILE
		#verify pin code
		$QMICLI -d $QMI_PORT --dms-uim-verify-pin=PIN,$pin_code
	else
		echo -e "APN=\nusername=\npassword=\nPIN=$pin_code"
	fi
    exit 0	
}

# sim card pin code protection
cell_pin_protection (){

        # check proxy status
        chk_proxy_status
	
	local pin_num="$1"
	local pin_enable="$2"
	local pin_current="$3"
	local par_fail="0"		
	# user does not give current pin
	[ $# -ne 3 ] && par_fail="1"
	[ x"$pin_num" != x"PIN" ] && [ x$pin_num != x"PIN2" ] && par_fail="1"
	[ x"$pin_enable" != x"enable" ] && [ x$pin_enable != x"disable" ] && par_fail="1"
		
	if [ $par_fail = "1" ]; then
		echo "Usage: cell_mgmt pin_protection [PIN|PIN2] [enable|disable] [current_PIN]"	
	    exit 1
    else
		$QMICLI -d $QMI_PORT --dms-uim-set-pin-protection=$pin_num,$pin_enable,$pin_current
	    exit 0
    fi
	
}

# cellular gps on
cell_gps_on () {
        local AT_PORT_NUM
if [ x"$id" == x"MC9090" ]; then
	echo -n -e 'ATE0\r\n' > ${CELL_PORT}
	sleep 1	
	echo -n -e 'AT!entercnd="A710"\r\n' > ${CELL_PORT}
	sleep 1	
        echo -e -n 'AT!custom="GPSENABLE",1\r\n' > ${CELL_PORT}
	sleep 1	
	echo -e -n 'AT!RESET\r\n' >  ${CELL_PORT}
	echo "GPS function is *ENABLE*"
else
        let AT_PORT_NUM=$INTERFACE*4+2
	echo -n -e 'AT^SGPSC="Engine","1"\r\n' > /dev/ttyUSB${AT_PORT_NUM}
        echo "GPS function is *ENABLE*"

fi
}

# cellular gps off
cell_gps_off () {
        local AT_PORT_NUM
if [ x"$id" == x"MC9090" ]; then
	echo -n -e 'ATE0\r\n' > ${CELL_PORT}
	sleep 1	
	echo -n -e 'AT!entercnd="A710"\r\n' > ${CELL_PORT}
	sleep 1	
        echo -e -n 'AT!custom="GPSENABLE",0\r\n' > ${CELL_PORT}
	sleep 1	
	echo -e -n 'AT!RESET\r\n' >  ${CELL_PORT}
	echo "GPS function is *DISABLE*"
else
        let AT_PORT_NUM=$INTERFACE*4+2
	echo -n -e 'AT^SGPSC="Engine","0"\r\n' > /dev/ttyUSB${AT_PORT_NUM}
	echo "GPS function is *DISABLE*"
fi
}

# AT command 
cell_at_cmd () {


cat > /tmp/cell_at_cmd.sh << EOF
result=""
[ -e /tmp/at_cmd.log ] && rm /tmp/at_cmd.log
cat ${CELL_PORT} >> /tmp/at_cmd.log &
echo -e -n 'ATE0\r\n' > ${CELL_PORT}
echo "please wait..."
sleep 1

echo -n -e '$1\r\n' > ${CELL_PORT}
sleep 2	

result=\$(cat /tmp/at_cmd.log)
ps aux | grep cat | awk '{print \$2}' | xargs kill -9

echo -e "\n--- AT COMMAND: $1 ---\n"
echo -e "\$result\n"
EOF

chmod +x /tmp/cell_at_cmd.sh

/tmp/cell_at_cmd.sh 2>/dev/null



}

#
cell_check_module () {

	local err
	local device="${CELL_PORT}"
	[ x"$1" != x"" ] && device="$1"
	# if cellular module doesn't exist
cat > /tmp/cell_check_module.sh << EOF
#!/bin/bash
	rm /tmp/check_module.log 2>/dev/null
	echo "" > ${device} 2>/dev/null 
EOF
	chmod +x /tmp/cell_check_module.sh
	/tmp/cell_check_module.sh 2>'/tmp/check_module_log' > /dev/null
	#cat /tmp/check_module_log
	module_err="$(cat /tmp/check_module_log | grep "No such device")"
	
	if [ x"$module_err" != x"" ]; then 
		echo "Please insert the cellular module and reboot."
		return "1"
	else
		return "0"
	fi
	rm /tmp/cell_check_module.sh 2>/dev/null
	rm /tmp/check_module_log 2>/dev/null
}

# chekc current carrier
cell_check_carrier () {

        # check proxy status
        chk_proxy_status

	# chekc module status 
	cell_check_module 2>/dev/null
	[ x"$?" != x"0" ] && exit
    
    if [ x"$id" == x"MC7304" ] || [ x"$id" == x"MC7354" ]; then

	local module_info=""
	local time="4"
	echo -n -e 'ATE0\r\n' > ${CELL_PORT}
	#wait
	sleep 1	
	# enable password protected command
	echo -n -e 'AT!entercnd="A710"\r\n' > ${CELL_PORT}
	#wait
	sleep 1	
	echo -n -e 'AT!GOBISETIMAGEPREF?\r\n' > ${CELL_PORT} 
	sleep 2
	
	module_info=$(head -n +20 ${CELL_PORT})

	#preffered
	local pre_fw=$(echo "$module_info" |grep "pre" | grep "fw" | awk -F: '{print $2}') && pre_fw=${pre_fw// /}
	local pre_carrier_name=$(echo "$module_info"|grep "pre" | grep "carrier" | awk -F: '{print $2}') && \
		pre_carrier_name=${pre_carrier_name// /}	
	local pre_config=$(echo "$module_info"|grep "pre" | grep "config" | awk -F: '{print $2}' ) && \
		pre_config=${pre_config// /}
	
	#current
	local fw=$(echo "$module_info" |grep "current" | grep "fw" | awk -F: '{print $2}') && fw=${fw// /}
	local carrier_name=$(echo "$module_info"|grep "current" | grep "carrier" | awk -F: '{print $2}') && \
		carrier_name=${carrier_name// /}	
	local config=$(echo "$module_info"|grep "current" | grep "config" | awk -F: '{print $2}' ) && \
		config=${config// /}

	echo "----------Carrier Info----------"
	echo "preffered firmware=$pre_fw"
	echo "preffered carrier name=$pre_carrier_name"
	echo "preffered carrier config=$pre_config"
	
	echo "firmware=$fw"
	echo "carrier name=$carrier_name"
	echo "carrier config=$config"
	echo -e "--------------------------------"
        exit 0
    elif [ x"$id" == x"MC9090" ]; then
        $QMICLI -d ${QMI_PORT} --dms-list-stored-images
        exit 0 
    else    
        echo "Check Carrier Frequency Bands support for MC7354 MC7304 MC9090"
        exit 1 
    fi
}

# switching between US carrier frequency bands
cell_switch_carrier () {
	
        # check proxy status
        chk_proxy_status

	# chekc module information
	cell_check_module
	[ x"$?" != x"0" ] && exit
	
    if [ x"$id" == x"MC7354" ]; then
	
        local ISP=$1	
	    local module_info=""
	    local choice="1"	
	    local cmd="AT!GOBISETIMAGEPREF="
	    
	    echo -n -e 'ATE0\r\n' > ${CELL_PORT}
	    sleep 1	
	    # enable password protected command
	    echo -n -e 'AT!entercnd="A710"\r\n' > ${CELL_PORT}
	    sleep 2
	    #wait
	    
	    echo "----------switch_carrier------------"	

	    # use AT+CGMR to get firmware infomation
	    echo -n -e 'AT+CGMR\r\n' > ${CELL_PORT} 
	    sleep 1
	    module_info=$(head -n +5 ${CELL_PORT} | grep "_" )
	    module_info=${module_info/*_/}
	    module_info=${module_info/ */}
	    fw="$module_info"
	    # use AT!priid? to get carrier information 
	    echo -n -e 'AT!priid?\r\n' > ${CELL_PORT}
	    sleep 1 
	    
	    [ x"$1" = x"ATT" ] && carrier="ATT"
	    [ x"$1" = x"Verizon" ] && carrier="VZW"
	    [ x"$1" = x"Sprint" ] && carrier="SPRINT"
	    [ x"$1" = x"Generic" ] && carrier="GENNA-UMTS"

	    module_info=$(head -n +18 ${CELL_PORT} | grep "$carrier")
	    config=$(echo $module_info | awk 'BEGIN {FS="_"}; {print $7}' )
	    config=${config}_$(echo $module_info | awk 'BEGIN {FS="_"}; {print $8}' )
	    
	    
	    case "$1" in
	    	Verizon)	
	    		cmd="${cmd}\"${fw}\",\"VZW\",\"VZW_${config}\"\r\n"
	    		;;
	    	ATT)
	    		cmd="${cmd}\"${fw}\",\"ATT\",\"ATT_${config}\"\r\n"
	    		;;
	    	Sprint)
	    		cmd="${cmd}\"${fw}\",\"SPRINT\",\"SPRINT_${config}\"\r\n"
	    		;;
	    	Generic)
	    		cmd="${cmd}\"${fw}\",\"GENNA-UMTS\",\"GENNA-UMTS_${config}\"\r\n"
	    		;;
	    	*)	
	    		echo -e "\033[1;37;40mUsage: \033[0;37;40m"
	    		echo -e "\033[1;37;40m       switch_carrier [$CARRIER]\033[0;37;40m"	
	    		choice="0"
	    		;;
	    esac
	    
	    # switching function is MC7354 only
	    if [ "$choice" -eq "1" ]; then
	    	
	    	echo "cmd=$cmd"
	    	echo -n -e 'ATE0\r\n' > ${CELL_PORT} 
	    	sleep 1
	    	echo -n -e 'AT!entercnd="A710"\r\n' > ${CELL_PORT}
	    	sleep 1
	    	echo -n -e "$cmd" > ${CELL_PORT}
	    	sleep 2
	    	
	    	echo "wait for power off..."
	    	cell_mgmt power_off
	    	rm -rf /dev/ttyUSB0
	    	rm -rf /dev/ttyUSB1
	    	echo "wait for power on..."
	    	cell_mgmt power_on
	    	
	    	while [ ! -e "${CELL_PORT}" ]
	    	do
	    		sleep 1
	    	done
	    	echo "done"
	    
	    fi
    elif [ x"$id" == x"MC9090" ]; then
	    carrier=""
        [ x"$1" = x"ATT" ] && carrier="pri0"
	    [ x"$1" = x"Verizon" ] && carrier="pri2"
	    [ x"$1" = x"Sprint" ] && carrier="pri1"
	    [ x"$1" = x"Generic" ] && carrier="pri0"
        if [ x"$carrier" == x"" ]; then
            echo -e "\033[1;37;40mUsage: \033[0;37;40m"
            echo -e "\033[1;37;40m       switch_carrier [$CARRIER]\033[0;37;40m"
            exit 1
        fi
        $QMICLI -d ${QMI_PORT} --dms-select-stored-image=modem2,$carrier 
        sleep 1
        $QMICLI -d ${QMI_PORT} --dms-set-operating-mode=offline
        sleep 1
        $QMICLI -d ${QMI_PORT} --dms-set-operating-mode=reset
        sleep 1 
        exit 0
    else
	   	echo "Switching Carrier Frequency Bands support for MC7354 MC9090"
        exit 1
    fi
}

# cell_mgmt interface
cell_interface () {

	case $1 in
		"0" | "1" | "2" | "3")
	                if [ -f $CELL_MGMT_PROFILE ]; then
	                        sed -i "s/INTERFACE=.*/INTERFACE=$1/" $CELL_MGMT_PROFILE
	                else
	                        echo "INTERFACE=$1" >> $CELL_MGMT_PROFILE
	                fi
	                echo "set interface=$1"
	                exit 0
			;;
                "")
                        ALL_INTERFACE=($(ip link | grep wwan | awk -F ":" '{print $2}'))
                        for (( i=0 ; i<${#ALL_INTERFACE[@]} ; i++ ))
                        do
                                echo "[$i] ${ALL_INTERFACE[$i]}$([ x$i == x$INTERFACE ] && echo '   <Current>')"
			done
                        
                        ;;
		*)
	                echo "Usage: cell_mgmt \"interface\" [0~3]"
	                echo "example:"
	                echo "          cell_mgmt interface 0"
	                exit 1
			;;
	esac

}

# cell_mgmt version
cell_version () {
    echo "cell_mgmt"
    echo "version:$VERSION"
}

# show cell_mgmt usage list
cell_usage () {
        echo -e "\033[1;37;40mcell_mgmt support sierra MC9090 MC7304 MC7354\033[0;37;40m"
	echo -e "\033[1;37;40mUsage: \033[0;37;40m"
	echo -e "\033[1;37;40m      $0 \033[0;37;40m[\033[4;37;40mOPTIONS\033[0;37;40m]\n"
	echo -e "\033[1;37;40mOPTIONS\033[0;37;40m"
	#start
	echo -e "\033[1;37;40m       start\033[0;37;40m [APN=[APN],Username=[user],Password=[pass],PIN=[pin_code]]"
	echo -e "		Start network."
	echo -e ""
	echo -e "		example:"
	echo -e "		        cell_mgmt start"
	echo -e "		        cell_mgmt start APN=internet"
	echo -e "		        cell_mgmt start APN=internet PIN=0000"
	echo -e "		        cell_mgmt start APN=internet Username=moxa Password=pass PIN=0000"
	#stop
	echo -e "\033[1;37;40m       stop\033[0;37;40m"	
	echo -e "		Stop network."
	#restart
	echo -e "\033[1;37;40m       restart\033[0;37;40m"	
	echo -e "		Restart network."
	#reset
	echo -e "\033[1;37;40m       reset\033[0;37;40m"	
	echo -e "		Reset cellular."
	#power on
	echo -e "\033[1;37;40m       power_on\033[0;37;40m"	
	echo -e "		Power ON."
	#power off 
	echo -e "\033[1;37;40m       power_off\033[0;37;40m"	
	echo -e "		Power OFF."
	#gps on
	echo -e "\033[1;37;40m       gps_on\033[0;37;40m"	
	echo -e "		GPS ON."
	#gps off 
	echo -e "\033[1;37;40m       gps_off\033[0;37;40m"	
	echo -e "		GPS OFF."
	#status 
	echo -e "\033[1;37;40m       status\033[0;37;40m"	
	echo -e "		Query network connection status."
	#signal 
	echo -e "\033[1;37;40m       signal\033[0;37;40m"	
	echo -e "		Get signal strength."
	##set_default 
	#echo -e "\033[1;37;40m       set_default\033[0;37;40m"	
	#echo -e "		RESET module to factory default."
	#at 
	echo -e "\033[1;37;40m       at\033[0;37;40m ['AT_COMMAND']"	
	echo -e "		Input AT Command."
	echo -e "		Must use SINGLE QUOTATION to enclose AT Command."
	echo -e ""
	echo -e "		example:"
	echo -e "		        cell_mgmt at 'AT+CSQ'"
	#sim_status
	echo -e "\033[1;37;40m       sim_status\033[0;37;40m"	
	echo -e "		Query sim card status."
	#set_pin 
	echo -e "\033[1;37;40m       set_pin [PIN]\033[0;37;40m"	
	echo -e "		Set PIN code to configuration file and verify."
	#protection_pin 
	echo -e "\033[1;37;40m       pin_protection [PIN|PIN2] [enable|disable] [current_PIN]\033[0;37;40m"	
	echo -e "		Set PIN protection in the UIM."
	echo -e ""
	echo -e "		example:"
	echo -e "		        cell_mgmt pin_protection PIN enable 0000"
	##check_carrier 
	#echo -e "\033[1;37;40m       check_carrier\033[0;37;40m"	
	#echo -e "		Check current carrier."
	##switch_carrier 
	#echo -e "\033[1;37;40m       switch_carrier [$CARRIER]\033[0;37;40m"	
	#echo -e "		Switching between US carrier frequency bands."
	#version
        echo -e "\033[1;37;40m       version\033[0;37;40m"	
	echo -e "		Cellular management version."
	#setinterface
        echo -e "\033[1;37;40m       interface [num]\033[0;37;40m"	
	echo -e "		Set the interface wwan[num] for cell_mgmt."

}


case "$1" in
	start)
		cell_start $2 $3 $4 $5
		;;
	stop)
		cell_stop
		;;
	reset)
		cell_reset
		;;
	restart)
		cell_restart
		;;
	gps_on)
		cell_gps_on
		;;
	gps_off)
		cell_gps_off
		;;
	power_on)
		cell_power_on
		;;
	power_off)
		cell_power_off
		;;
	status)
		cell_status
		;;
	signal)
		cell_signal
		;;
#	set_default)
#		cell_set_to_default
#		;;
	sim_status)
		cell_sim_status
                ;;
        pin_code_status)
                cell_pin_code_status
                ;;
	set_pin)
		cell_set_pin $2
		;;
	pin_protection)
		cell_pin_protection $2 $3 $4
		;;
#	check_carrier)
#		cell_check_carrier
#		;;
#	switch_carrier)
#		cell_switch_carrier $2
#		;;
	at)
		cell_at_cmd $2
		;;
	version)
                cell_version
                ;;
        interface)
		cell_interface $2
		;;
	help)
		cell_usage	
		;;
	*)
		cell_usage
		exit 3
		;;
esac

