#!/bin/sh
#
# Copyright 2003 Meru Networks
# All rights reserved.
#

if [ -f /etc/init.d/platform_params ]; then
        . /etc/init.d/platform_params
else
        echo "/etc/init.d/platform_params must exist to use $0"; exit 1
fi

#
# Set Meru common functions
#
[ "$LOG" ] || LOG=/opt/meru/var/log/meru_init.log 

CURVER=`/opt/wlan/bin/showver -b`

PATH=/opt/meru/bin:/usr/local/sbin:/sbin:/usr/sbin:/usr/local/bin:/bin:/usr/bin
export PATH

cleanup()
{
	[ "$tmp" ]  && rm -f $tmp
	[ "$tmp2" ] && rm -f $tmp
	[ "$tmp3" ] && rm -f $tmp
}

#
# Print a warning message
# If the terminal is not the serial console then send it there too.
#
warning()
{
    [ "$1" ] && {
        echo
        echo WARNING $0: "$1" | sed 's/\/opt\/meru\///' | tee -a $LOG
        echo
        [ -w /dev/ttyS0 ] && {
            [ "`tty`" = "/dev/ttyS0" ] || {
                echo  > /dev/ttyS0     
				echo WARNING $0: "$1" | sed 's/\/opt\/meru\///' > /dev/ttyS0
                echo > /dev/ttyS0           
            }
        }
    }
}



#
# Print a message and exit 
# If the terminal is not the serial console then send it there too.
#
fail()
{
	[ "$1" ] && {
		echo
		echo ERROR : "$1"  | sed 's/\/opt\/meru\///' | tee -a $LOG
		echo
		[ -w /dev/ttyS0 ] && {
			[ "`tty`" = "/dev/ttyS0" ] || {
				echo  > /dev/ttyS0     
				echo ERROR : "$1" | sed 's/\/opt\/meru\///' > /dev/ttyS0
				echo > /dev/ttyS0           
			}
		}
	}
	cleanup
	exit 1
}

#
# Make sure the pid of the process running matches the pidfile.
# Assumes that the process is not in our process group. i.e. it was running
# before this program started.
#
vrfy_pid()
{
	vp_pid=""
	vp_pid=`pgrep -P 1 -f "$1"`
	[ "$vp_pid" = "" ] && return

	if [ -f $PIDFILE ]; then
		[ "$vp_pid"  = "`cat $PIDFILE`" ] || echo $vp_pid > $PIDFILE
	else
		echo $vp_pid > $PIDFILE
	fi
}

#                                                                                       
# Verify that a process is running               
# $1 - name of process or pid 
#                                          
vrfy()                            
{                                                                                           
        [ "$1" ] || return 1     
                                 
        if expr  $1 + 1 >/dev/null 2>&1; then
                ps -p $1 >/dev/null && return 0
        else                                                   
                pgrep -f "$1" >/dev/null && return 0                       
        fi                    
        return 1
}     

#
# Verify that a process is running
# $1 - pid number in process pid file
#
# When a process is not running, return 1 then monit starts the process
# When a process is running, return 0 as following cases
#      - If its pid file does not exist, kill the process 
#      and then let monit start the process at next interval.
#      - If its pid file does not contain pid number, kill the process 
#      and then let monit start the process at next interval.
#      - If running process is not matched to its pid in the pid file,
#      kill the process and then let monit start the process at next interval.
#      - If process has multiple instances, kill the process
#      and then let monit start the process at next interval.
#
vrfy_combo()
{
    MLOG="/opt/wlan/var/log/monit.log"
 
    # check if process is not running
    #
    pid=`pgrep -P 1 -f $PROC`
    [ "$pid" ] || {

        # cleanup if previous pid file exists
        rm -f $PIDFILE
        return 1
    }

    # check if running process is matched to pid in its pid file
    [ "$1" ] && {

        [ "`echo $pid | grep $1`" ] || {

            echo -n [`date`] $MNAME killed by mismatched P:$pid F:$1 >> $MLOG
            echo >> $MLOG

            # kill all processes
            pkill -9 -f $PROC 2>/dev/null
            rm -f $PIDFILE
        }

        return 0
    }

    # if pid file does not exist or pid file does not contain pid number,
    # kill process and then let monit start the process at next interval

    echo -n [`date`] $PIDFILE is missing. kill $MNAME to recover its pid file. >> $MLOG
    echo >> $MLOG

    pkill -9 -f $PROC 2>/dev/null
    rm -f $PIDFILE

    return 0
}

#
# Write the pid file.
# The kernel may not have gotten around to updating the proc table
# so loop until it works.
#
# Kannan: 2006-01-18: Do not write the pid to the file until you 
# actually know that there is a pid to write to the file.  Otherwise
# monit could pick up an empty file and log erroneous error/warning
# messages to monit.log.
#
write_pid()
{
    wp_cnt=0
    if [ "$LOG" ]; then
        echo "Process $PROC is being invoked with parent pid $$" >> $LOG
    fi
    while true
      do
      [ $wp_cnt -gt 30 ] && {
          break
      }

      pidval=`pgrep -P $$ -f $PROC`
      if [ "$pidval" ]; then
          echo -n [`date`] Writing $PROC pid $pidval to $PIDFILE >> $LOG
          echo >> $LOG	
          echo $pidval > $PIDFILE
          sync
          sync
          break
      fi

      wp_cnt=`expr $wp_cnt + 1`
      sleep .2

    done

    if [ -s $PIDFILE ]; then
        echo -n [`date`] INFO: $PROC started in `expr 2 + $wp_cnt` tenths seconds. >> $LOG
        echo >> $LOG	
    fi
}

# Bug fix 24851
# Moving writePO_pid from ping_ouis file, so that np1adv and np1slave can access this function or sub routine
writePO_pid()
{
    wp_cnt=0
    while true
    do
        [ $wp_cnt -gt 30 ] && {
            break
        }
        pidval=`pgrep -f $PROC`
        if [ "$pidval" ]; then
            echo -n [`date`] Writing $PROC pid $pidval to $PIDFILE >> $LOG
            echo >> $LOG	
            echo $pidval > $PIDFILE
            sync
            sync
            break
        fi

        wp_cnt=`expr $wp_cnt + 1`
        sleep .2
    done

    if [ -s $PIDFILE ]; then
        echo -n [`date`] INFO: $PROC started in `expr 2 + $wp_cnt` tenths seconds. >> $LOG
        echo >> $LOG	
    fi
}

writeP1_pid()
{
    wp_cnt=0
    while true
    do
        [ $wp_cnt -gt 30 ] && {
            break
        }
        pidval=`pgrep -P 1 -f $PROC`
        if [ "$pidval" ]; then
            echo -n [`date`] Writing $PROC pid $pidval to $PIDFILE >> $LOG
            echo >> $LOG	
            echo $pidval > $PIDFILE
            sync
            sync
            break
        fi

        wp_cnt=`expr $wp_cnt + 1`
        sleep .2
    done

    if [ -s $PIDFILE ]; then
        echo -n [`date`] INFO: $PROC started in `expr 2 + $wp_cnt` tenths seconds. >> $LOG
        echo >> $LOG	
    fi
}


#
# Send a process a cleanup signal and go into a loop waiting for it to die.
# Time out and send signal 9
# $1 - name of process or pid
# $2 - timeout
# $3 - Cleanup signal
#
die()
{
	die_max=120
	die_timeout=3
	die_sig=15
	die_proc=$1
	die_pid=

    #kill -9 timeout
	kill_9_timeout=10
	
	[ "$die_proc" ] || return

	[ "$2" ] && die_timeout=$2
	expr $die_timeout + 1 >/dev/null 2>&1 || fail "timout not integer"
	[ "$3" ] && die_sig=$3
	expr $die_sig + 1 >/dev/null 2>&1 || fail "signal not integer"

	expr $die_proc + 1 >/dev/null 2>&1 && die_pid=$die_proc

	vrfy $die_proc || return
	if [ "$die_pid" ]; then
		echo -n [`date`] Sent signal $die_sig to $PROC with pid $die_pid >> $LOG
		echo >> $LOG
		kill -$die_sig $die_pid 2>/dev/null
	else
		echo -n [`date`] Sent signal $die_sig to $die_proc >> $LOG
		echo >> $LOG
		pkill -$die_sig -f $die_proc 2>/dev/null
	fi

	timer=0
	while /bin/true
	do
		vrfy $die_proc || return
		sleep 1
		timer=`expr $timer + 1`
		[ $timer -gt $die_timeout ] && break
		[ $timer -gt $die_max ] && break
		[ `expr $timer % 5` = 0 ] && echo "Waiting for $die_proc to shutdown ..." | tee -a $LOG
	done
	echo -n [`date`] $0 $Warning: process did not shut down cleanly. >> $LOG
	echo >> $LOG
	if [ "$die_pid" ]; then
		timer=0
		echo -n [`date`] Sent signal 9 to $PROC with pid $die_pid >> $LOG
		echo >> $LOG
  		while /bin/true
		do
			kill -9 $die_pid 2>/dev/null
			timer=`expr $timer + 1`
			sleep 1
			vrfy $die_proc || return
			[ $timer -gt $kill_9_timeout ] && {
				logger -p local1.crit -t CRITICAL "Error: System is unrecoverable state $die_proc"
				break
			}
	 	done	
	else
		timer=0
		echo -n [`date`] Sent signal 9 to $die_proc >> $LOG
		echo >> $LOG
  		while /bin/true
		do
			pkill -9 -f $die_proc 2>/dev/null
			timer=`expr $timer + 1`
			sleep 1
			vrfy $die_proc || return
			[ $timer -gt $kill_9_timeout ] && {
				logger -p local1.crit -t CRITICAL "Error: System is unrecoverable state $die_proc"
				break
			}
	 	done	
	fi
}



# 
# Kannan: 2006-02-03: Renaming original "retry_start_with_monit" with
# start_with_monit. Originally this routine retried starting the task with
# monit multiple times.  However, this beats the purpose of monit which has
# exactly the same reponsibility (restarting the task if it does not start).
# This is particularly so, starting with Release 3.2, where monit is started in
# inittab.  Hereafter this routine's name is a misnomer, in a direct sense (this
# routine will not ask monit explicity to restart $MNAME multiple times)
# but not in an indirect sense (monit will retry multiple times by itself).  
#
# This routine will only start $MNAME once.
#
start_with_monit()
{
    MNAME=$1
    monit -c /opt/wlan/etc/monit.conf start $MNAME
    i=0
    while ! vrfy $MNAME
      do
      let "i++"
      sleep 1
      [ $i -gt 12 ] && {
          echo "Process $MNAME did not come up. Will retry again"
          break;
      }
    done
}

stop_with_monit()
{
    MNAME=$1
    monit -c /opt/wlan/etc/monit.conf stop $MNAME
}

restart_with_monit()
{
    MNAME=$1
    monit -c /opt/wlan/etc/monit.conf restart $MNAME
}

#
# Meru configuration
#

#
# Read meru configuration file and set parameters.
# Log values if LOG is set.
#
set_params()
{
    MCONFIG=/opt/wlan/etc/meru.conf
    
    if [ "$MERUCONFIG" ]; then
		#
		# Environment can override
		#
        [ -f $MERUCONFIG ] || fail "$MERUCONFIG does not exist".
        . $MERUCONFIG
    elif [ -f $MCONFIG ]; then
        . $MCONFIG
    else
        echo "$0: ERROR: Cannot find the configuration file: $MCONFIG"
        exit 1
    fi
    
    SECOND_UDP_IF=meru2

    . /etc/init.d/platform_params 
    set_platform_params
    # we source it here again in case it didn't exist at start of upgrade

    export NODE_TYPE UDP_IF SECOND_INTERFACE_MODE REAL_IF DHCP_SERVER_IP 
    export MERU_ESSID ASC_ATS_IF HIGH_AVAILABILITY_STATE
    export FIRST_IF SECOND_IF REAL_IF SECOND_UDP_IF DUMP_DEV
    
    grep NODE_TYPE $LOG >/dev/null 2>&1 || {
        echo "NODE_TYPE = $NODE_TYPE" >> $LOG
        echo "UDP_IF = $UDP_IF" >> $LOG
        echo "REAL_IF = $REAL_IF" >> $LOG
        echo "FIRST_IF = $FIRST_IF" >> $LOG
        echo "SECOND_IF = $SECOND_IF" >> $LOG
        echo "DHCP_SERVER_IP = $DHCP_SERVER_IP" >> $LOG
        echo "MERU_ESSID = $MERU_ESSID" >> $LOG
        echo "ASC_ATS_IF = $ASC_ATS_IF" >> $LOG
    }
    
	#
	# Read the following off the REAL_IF or UDP_IF and set these variables.
	#
    if [ -f /opt/wlan/var/run/rebridging ]; then
        [ "$UDP_IF" ] || fail "UDP_IF must be defined before starting the Meru sub-system"
        WIRELESS_SUBNET_ADDR=`ifconfig $UDP_IF | perl -ne 'if (/.*inet addr:(.+?)\s/) { print $1; }'`;
        WIRELESS_SUBNET_MASK=`ifconfig $UDP_IF | perl -ne 'if (/.*Mask:(.+?)\s/) { print $1; }'`;
        MERU_MAC=`ifconfig $UDP_IF | perl -ne 'if (/.*HWaddr (.+?)\s/) { print $1; }'`
        WIRELESS_SUBNET_BCST=`ipcalc -b $WIRELESS_SUBNET_ADDR $WIRELESS_SUBNET_MASK 2>/dev/null | cut -d= -f 2`
        if [ "$SECOND_INTERFACE_MODE" = "active" ]; then
            SECOND_SUBNET_ADDR=`ifconfig $SECOND_UDP_IF | perl -ne 'if (/.*inet addr:(.+?)\s/) { print $1; }'`;
            SECOND_SUBNET_MASK=`ifconfig $SECOND_UDP_IF | perl -ne 'if (/.*Mask:(.+?)\s/) { print $1; }'`;
            SECOND_SUBNET_BCST=`ipcalc -b $SECOND_SUBNET_ADDR $SECOND_SUBNET_MASK 2>/dev/null | cut -d= -f 2`
        fi
        
    else
        [ "$REAL_IF" ] || fail "REAL_IF must be defined before starting the Meru sub-system"
        WIRELESS_SUBNET_ADDR=`ifconfig $REAL_IF | perl -ne 'if (/.*inet addr:(.+?)\s/) { print $1; }'`;
        WIRELESS_SUBNET_MASK=`ifconfig $REAL_IF | perl -ne 'if (/.*Mask:(.+?)\s/) { print $1; }'`;
        MERU_MAC=`ifconfig $REAL_IF | perl -ne 'if (/.*HWaddr (.+?)\s/) { print $1; }'`
        WIRELESS_SUBNET_BCST=`ipcalc -b $WIRELESS_SUBNET_ADDR $WIRELESS_SUBNET_MASK 2>/dev/null | cut -d= -f 2`
        if [ "$SECOND_INTERFACE_MODE" = "active" ]; then
            SECOND_SUBNET_ADDR=`ifconfig $SECOND_IF | perl -ne 'if (/.*inet addr:(.+?)\s/) { print $1; }'`;
            SECOND_SUBNET_MASK=`ifconfig $SECOND_IF | perl -ne 'if (/.*Mask:(.+?)\s/) { print $1; }'`;
            SECOND_SUBNET_BCST=`ipcalc -b $SECOND_SUBNET_ADDR $SECOND_SUBNET_MASK 2>/dev/null | cut -d= -f 2`
        fi
    fi
    export WIRELESS_SUBNET_ADDR WIRELESS_SUBNET_MASK MERU_MAC WIRELESS_SUBNET_BCST
    if [ "$SECOND_INTERFACE_MODE" = "active" ]; then
        export SECOND_SUBNET_ADDR SECOND_SUBNET_MASK SECOND_SUBNET_BCST
    fi
    
    grep WIRELESS_SUBNET_ADDR $LOG >/dev/null 2>&1 || {
        echo "WIRELESS_SUBNET_ADDR = $WIRELESS_SUBNET_ADDR" >> $LOG
        echo "WIRELESS_SUBNET_MASK = $WIRELESS_SUBNET_MASK">> $LOG
        echo "MERU_MAC = $MERU_MAC">> $LOG
        echo "WIRELESS_SUBNET_BCST = $WIRELESS_SUBNET_BCST">> $LOG
        echo >> $LOG
    }
}

DB_DIR=/opt/wlan/var/run/running-db
export DB_DIR
BACKUP_DIR=/opt/wlan/backup
export BACKUP_DIR

pull_db()
{
   echo "meru-functions:pull_db" >> $LOG 
    mkdir -p $DB_DIR
    cp /opt/wlan/etc/meru.conf $DB_DIR/
    cp /opt/wlan/etc/country_codes/country.conf $DB_DIR/
    cp /etc/sysconfig/network-scripts/ifcfg-* $DB_DIR/
    cp /etc/sysconfig/network $DB_DIR/
    cp /etc/hosts $DB_DIR/
    if [ -f /opt/wlan/etc/resolv.conf ]; then
	cp /opt/wlan/etc/resolv.conf /etc/resolv.conf
	rm /opt/wlan/etc/resolv.conf
    fi
    if [ -f /opt/wlan/etc/syslog.conf ]; then
	cp /opt/wlan/etc/syslog.conf /etc/syslog.conf
	rm /opt/wlan/etc/syslog.conf
    fi
    cp /etc/syslog.conf $DB_DIR/
    if [ -f /opt/wlan/etc/ceflog.conf ]; then
	cp /opt/wlan/etc/ceflog.conf /etc/ceflog.conf
	rm /opt/wlan/etc/ceflog.conf
    fi
    cp /etc/ceflog.conf $DB_DIR/
    [ -f /etc/resolv.conf ] || touch /etc/resolv.conf
    cp /etc/resolv.conf $DB_DIR/
    [ -f /opt/wlan/etc/merudb.dbs ] && cp /opt/wlan/etc/merudb.dbs $DB_DIR/
    sync
}

commit_db()
{
    echo "meru-functions:commit_db" >> $LOG 
    cp $DB_DIR/meru.conf /opt/wlan/etc/
    cp $DB_DIR/country.conf /opt/wlan/etc/country_codes/
    rm -f /etc/sysconfig/network-scripts/ifcfg-eth*
    cp $DB_DIR/ifcfg-* /etc/sysconfig/network-scripts/
    cp $DB_DIR/network /etc/sysconfig/
    cp $DB_DIR/hosts /etc/
    cp $DB_DIR/syslog.conf /etc/
    cp $DB_DIR/ceflog.conf /etc/
    [ -f $DB_DIR/resolv.conf ] || touch $DB_DIR/resolv.conf
    cp $DB_DIR/resolv.conf /etc/resolv.conf
    /opt/wlan/bin/ioscli -c "show controller" > /dev/null
    if [ $? == 0 ]
    then
    	/opt/wlan/bin/ioscli -c "safe-backup /opt/wlan/etc/merudb.dbs"
    else
	cp $DB_DIR/merudb.dbs /opt/wlan/etc/
    fi
    sync
}

backup_db()
{
   echo "meru-functions:backup_db" >> /etc/init.d/up.log
    # Backup from running config to file specified by first argument.
    [ -f $DB_DIR/resolv.conf ] || touch $DB_DIR/resolv.conf

    if [ "$1" == "" ]; then
        dbFile="dflt_backup"
    else
        dbFile="$1"
    fi
    cd $DB_DIR
    mkdir -p $BACKUP_DIR/tmp
    /opt/wlan/bin/ioscli -c "safe-backup $BACKUP_DIR/tmp/merudb.bak"
    cp -f meru.conf \
	    country.conf \
            ifcfg-* \
            network \
            hosts \
            syslog.conf \
            ceflog.conf \
            resolv.conf \
	    $BACKUP_DIR/tmp/ > /dev/null 2>&1
    cd $BACKUP_DIR/tmp
    /bin/tar -cf $BACKUP_DIR/tmpdb.tar \
            meru.conf \
	    country.conf \
            ifcfg-* \
            network \
            hosts \
            syslog.conf \
            ceflog.conf \
            merudb.bak \
            resolv.conf > /dev/null 2>&1
    cd $BACKUP_DIR
    rm -rf $BACKUP_DIR/tmp
    /bin/gzip tmpdb.tar > /dev/null 2>&1
    if [ ! -f tmpdb.tar.gz ]; then
        rm -f tmpdb.tar
        sync
        echo "Error: Copy of running configuration to $dbFile failed." >> $LOG
        return 1
    fi
    if [ "$2" == "upgrade" ]; then
	mv -f tmpdb.tar.gz ${dbFile}
    else
	mv -f tmpdb.tar.gz ${dbFile}.${CURVER}.tar.gz
    fi
    sync

    if [ -f ${dbFile}.${CURVER}.tar.gz -o -f ${dbFile} ]; then
        # echo "Running configuration successfully copied to $dbFile." >> $LOG
        return 0
    else
        echo "Error: Copy of running configuration to $dbFile failed." >> $LOG
        return 1
    fi
}

restore_db()
{
    echo "meru-functions:restore_db" >> $LOG 
    # Restore backup file specified by first argument to startup config.
    if [ "$1" == "" ]; then
        dbFile="dflt_backup"
    else
        dbFile="$1"
    fi

    cd $BACKUP_DIR

    realFile=$dbFile
    if [ ! -f ${dbFile}.${CURVER}.tar.gz ]; then
	if [ "$2" != "upgrade" ]; then
	    echo "Error: No such configuration file $dbFile." >> $LOG
	    return 1
	else
	    if [ ! -f ${dbFile} ]; then
		# No image to downgrade to.  Fail silently.
        # Just return 0 since on upgrade this file may not always
        # exist unless you upgrade->downgrade->upgrade 
		return 0 
	    fi
	fi
    else
	# Assume dbfile has curver
	realFile=${dbFile}.${CURVER}.tar.gz
    fi

    cp -f $realFile tmpdb.tar.gz
    /bin/gunzip tmpdb.tar.gz > /dev/null 2>&1
    if [ ! -f tmpdb.tar ]; then
        rm -f tmpdb.tar.gz
        sync
        echo "Error: Invalid configuration file $dbFile." >> $LOG
        return 1
    fi
    /bin/tar -xf tmpdb.tar > /dev/null 2>&1
    rm -f tmpdb.tar

    if [ -f meru.conf ]; then
        mv -f meru.conf /opt/wlan/etc/
        [ -e country.conf ] && mv -f country.conf /opt/wlan/etc/country_codes/
        mv -f ifcfg-* /etc/sysconfig/network-scripts/
        mv -f network /etc/sysconfig/
        mv -f hosts /etc/
        mv -f syslog.conf /etc/
        mv -f ceflog.conf /etc/
        if [ -f merudb.bak ]; then
            mv -f merudb.bak /opt/wlan/etc/merudb.dbs
        else
            mv -f merudb.dbs /opt/wlan/etc/
        fi
        mv -f resolv.conf /etc/resolv.conf
        sync
        echo "Startup configuration successfully copied from $dbFile." >> $LOG
        return 0
    else
        sync
        echo "Error: Invalid configuration file $dbFile." >> $LOG
        return 1
    fi
}

verify_db()
{
    echo "meru-functions:verify_db" >> $LOG 
    BACKUP_DB_BASE=checkpoint-db-
    COUNT=1
    while [ $COUNT -le 4 ]; do
	cd /opt/wlan/etc
	/opt/wlan/bin/subsql -verify
	if [ $? != 0 ]; then
	    # Corrupted:  pull checkpoint
	    /bin/mv -f /opt/wlan/etc/merudb.dbs /opt/wlan/etc/merudb.dbs.corrupted$COUNT
	    restore_db ${BACKUP_DB_BASE}${COUNT}
	else
	    if [ $COUNT -eq 1 ]; then
		return 0
	    else
		return 1
	    fi
	fi
	let "COUNT++"
    done

    /bin/mv -f /opt/wlan/etc/merudb.dbs /opt/wlan/etc/merudb.dbs.corrupted$COUNT
    /opt/wlan/bin/wncagent /opt/wlan/etc/ -i

    return 1
}


vrfy_running_db()
{
        cd /opt/meru/var/run/running-db
        /opt/meru/bin/subsql -verify
        if [ $? != 0 ];then
                echo "Database corrupted,copying the startup database" >> $LOG
                /bin/cp -f /opt/meru/etc/merudb.dbs /opt/meru/var/run/running-db/
        fi
}

ssl_update()
{
	remotehost=$1
	user=$2
	secret=$3
	remotepath=$4
	SUCCESS=0
	ERROR=1
 
	ext=$(basename $remotepath | sed -e 's/\(.*\.\)\(.*\)/\2/g')
	
	if [ "$ext" = "pem" -o "$ext" = "pfx" ]; then
		mv /opt/wlan/cert/$(basename "$remotepath") /opt/wlan/cert/$(basename "$remotepath").bak
		cmd="copy scp://$user:$secret@$remotehost/$remotepath /opt/wlan/cert"
		echo cmd=$cmd
		/opt/wlan/bin/ioscli -c "$cmd"
		ls /opt/wlan/cert/$(basename "$remotepath")
		if [ $? -ne 0 ]; then
			mv /opt/wlan/cert/$(basename "$remotepath").bak /opt/wlan/cert/$(basename "$remotepath")
			exit $ERROR;
		else
			rm /opt/wlan/cert/$(basename "$remotepath").bak
		exit $SUCCESS;
		fi;
	else
		exit $ERROR;
	fi
}

ch_pw()
{
	user=$1
	secret=$2
	ROOT_UID=0         # Root has $UID 0.
	E_WRONG_USER=65    # Not root?
	E_NOSUCHUSER=70
	SUCCESS=0
	ERRORPASSWD=1
	if [ "$UID" -ne "$ROOT_UID" ]
		then
		exit $E_WRONG_USER
	fi
	grep -q "$user" /etc/passwd
	if [ $? -ne $SUCCESS ]
		then
		exit $E_NOSUCHUSER
	fi
	echo "$secret" | passwd --stdin "$user"
	if [ $? -ne $SUCCESS ]
		then
		exit $ERRORPASSWD
	fi
	exit $SUCCESS
}

captive_portal_set()
{
	cmd=$1
	ROOT_DIR="/opt/wlan/etc/ws"

	rm -f $ROOT_DIR/html.vpnlink

	if [ $cmd = "meru" ]; then
		ln -s $ROOT_DIR/html.vpn $ROOT_DIR/html.vpnlink	
		/usr/bin/pkill -USR1 xems
              /usr/bin/logger -p local1.notice -t system "[MODIFY:Global Controller Parameters], WEB Log-in page is changed to default page"
		exit 0;
	fi
	if [ $cmd = "custom" ]; then
		ln -s $ROOT_DIR/html.vpn.custom $ROOT_DIR/html.vpnlink	
		echo "    Notice:Using GUI be sure to Import files!"
		/usr/bin/pkill -USR1 xems
              /usr/bin/logger -p local1.notice -t system "[MODIFY:Global Controller Parameters], WEB Log-in page is changed to custom page"
		exit 0;
	fi
	exit 1;
}

captive_portal_get()
{
	ROOT_DIR="/opt/wlan/etc/ws"
	x=`ls -i $ROOT_DIR/html.vpnlink`
	y=`ls -i $ROOT_DIR/html.vpn.custom`
	xx=`echo $x |  sed 's/[^0-9]*//g'`
	yy=`echo $y |  sed 's/[^0-9]*//g'`
	if [ "$xx" = "$yy" ]; then
		echo "custom"
		exit 0;
	else 
		echo "default"
		exit 0;
	fi
}

captive_portal_custom_area()
{
	ROOT_DIR="/opt/wlan/etc/ws"
	echo "Html Files"
	ls -lt $ROOT_DIR/html.vpn.custom
	
	echo "Image Files"
	ls -lt $ROOT_DIR/Images.vpn.custom
	exit 0;
}

#
# Convert logical interface numbers to real interfaces
#
logicalif_to_rebridging() 
{
	lif=$1

	if [ $lif -eq 1 ]; then
       		echo "meru"
	else
		echo "meru2"
	fi
}

#
# find if ha is on
# return 
#	0, if off, 
#	1, if HA on, 
is_ha_on()
{
	HAIF=`ifconfig | grep meru:0 | awk -F" " '{ print $1 }'`

	case $HAIF in
		meru:0)	echo "1";;
		*) echo "0";;
	esac
}

#
# check controller role
#
check_np1_role() {

        NP1SLAVE_CONF=/opt/wlan/np1/config/slave.conf
        NP1ROLE_FILE_f=/opt/wlan/np1/config/np1.role

        if [ -e ${NP1SLAVE_CONF} ]; then

                myrole=passive

                if [ -f ${NP1ROLE_FILE_f} ]; then

                        source ${NP1ROLE_FILE_f}
                        myrole=${NP1ROLE}
                fi

                if [ "${myrole}" = "passive" ]; then

                        echo "nplus1 cannot run the command in a Passive Slave."
                        exit 1
                fi
        fi
}

#
# Check the pid file.
#
check_pid()
{
    wp_cnt=0
    while true
    do
        [ $wp_cnt -gt 30 ] && {
            break
        }

        if [ -s $PIDFILE ]; then
            echo -n [`date`] Writing $PROC pid `cat $PIDFILE` to $PIDFILE >> $LOG
            echo >> $LOG
            echo -n [`date`] INFO: $PROC started in `expr 2 + $wp_cnt` tenths seconds. >> $LOG
            echo >> $LOG
            sync
            sync
            break
        fi

        wp_cnt=`expr $wp_cnt + 1`
        sleep .2

    done
}

#
# monit starts single process
#
monit_start_single_process() {

    vrfy_combo `cat $PIDFILE 2>/dev/null` && {
        return
    }

    echo "============ $0 start =================" >> $LOG
    cd /opt/wlan/etc

    $PROC >> $LOG 2>&1 &
    sleep $START_DELAY
    write_pid
    vrfy `cat $PIDFILE 2>/dev/null` || warning "$PROC did not start. Will try again."
}

#
# monit starts multi-threads 
#
monit_start_multi_threads() {

    vrfy_combo `cat $PIDFILE 2>/dev/null` && {
        return
    }

    echo "============ $0 start =================" >> $LOG
    cd /opt/wlan/etc

    $PROC >> $LOG 2>&1 &
    sleep $START_DELAY
    write_pid
    vrfy `cat $PIDFILE 2>/dev/null` || warning "$PROC did not start. Will try again."
}

#
# monit starts process
#
monit_stop_process() {

    echo "============ $0 stop =================" >> $LOG

    die "$PROC" $STOP_DELAY
    die `cat $PIDFILE 2>/dev/null` $STOP_DELAY

    rm -f $PIDFILE
}

#
# monit starts single process without writing pid file
#
monit_start_single_process_without_writepid() {

    vrfy_combo `cat $PIDFILE 2>/dev/null` && {
        return
    }

    echo "============ $0 start =================" >> $LOG
    cd /opt/wlan/etc

    $PROC >> $LOG 2>&1 &
    sleep $START_DELAY
    check_pid
    vrfy `cat $PIDFILE 2>/dev/null` || warning "$PROC did not start. Will try again."
}

#
# monit starts multi-threads without writing pid file
#
monit_start_multi_threads_without_writepid() {

    vrfy_combo `cat $PIDFILE 2>/dev/null` && {
        return
    }

    echo "============ $0 start =================" >> $LOG
    cd /opt/wlan/etc

    $PROC >> $LOG 2>&1 &
    sleep $START_DELAY
    check_pid
    vrfy `cat $PIDFILE 2>/dev/null` || warning "$PROC did not start. Will try again."
}

#
# monit conotrls single process
#
monit_control_single_process() {

    case "$1" in
        start)
                if vrfy monit; then
                        start_with_monit $MNAME 
                else
                        monit_start_single_process
                fi
                ;;
        stop)
                if vrfy monit; then
                        stop_with_monit $MNAME 
                else
                        monit_stop_process
                fi
                ;;
        restart)
                if vrfy monit; then
                        restart_with_monit $MNAME 
                else
                        monit_stop_process
                        monit_start_single_process
                fi
                ;;
        mstart)
                monit_start_single_process
                ;;
        mstop)
                monit_stop_process
                ;;
        *)
                echo $"Usage: $prog {start|stop|restart}"
    esac
}

#
# monit conotrls multi-threads 
#
monit_control_multi_threads() {

    case "$1" in
        start)
                if vrfy monit; then
                        start_with_monit $MNAME
                else
                        monit_start_multi_threads
                fi
                ;;
        stop)
                if vrfy monit; then
                        stop_with_monit $MNAME
                else
                        monit_stop_process
                fi
                ;;
        restart)
                if vrfy monit; then
                        restart_with_monit $MNAME
                else
                        monit_stop_process
                        monit_start_multi_threads
                fi
                ;;
        mstart)
                monit_start_multi_threads
                ;;
        mstop)
                monit_stop_process
                ;;
        *)
                echo $"Usage: $prog {start|stop|restart}"
    esac
}

#
# monit conotrls single process without writing pid file
#
monit_control_single_process_without_writepid() {

    case "$1" in
        start)
                if vrfy monit; then
                        start_with_monit $MNAME
                else
                        monit_start_single_process_without_writepid
                fi
                ;;
        stop)
                if vrfy monit; then
                        stop_with_monit $MNAME
                else
                        monit_stop_process
                fi
                ;;
        restart)
                if vrfy monit; then
                        restart_with_monit $MNAME
                else
                        monit_stop_process
                        monit_start_single_process_without_writepid
                fi
                ;;
        mstart)
                monit_start_single_process_without_writepid
                ;;
        mstop)
                monit_stop_process
                ;;
        *)
                echo $"Usage: $prog {start|stop|restart}"
    esac
}

#
# monit conotrls multi-threads without writing pid file
#
monit_control_multi_threads_without_writepid() {

    case "$1" in
        start)
                if vrfy monit; then
                        start_with_monit $MNAME
                else
                        monit_start_multi_threads_without_writepid
                fi
                ;;
        stop)
                if vrfy monit; then
                        stop_with_monit $MNAME
                else
                        monit_stop_process
                fi
                ;;
        restart)
                if vrfy monit; then
                        restart_with_monit $MNAME
                else
                        monit_stop_process
                        monit_start_multi_threads_without_writepid
                fi
                ;;
        mstart)
                monit_start_multi_threads_without_writepid
                ;;
        mstop)
                monit_stop_process
                ;;
        *)
                echo $"Usage: $prog {start|stop|restart}"
    esac
}
