#!/bin/sh
#################################################################
# File          init_acd_mlaa.sh                                #
# Description   Initialization of ACD/MLAA stuff:               #
#               - Creation of directories                       #
#               - Creation of symbolic links                    #
#               - Launch of ACD/MLAA engine                     #
#               - Logrotate configuration                       #
# Project       Alize Internet Access                           #
# Copyright     (c) Alcatel 2003                                #
# Author        tq                                              #
# Version       2.0                                             #
# Usage         type init_acd_mlaa.sh to perform the acd/mlaa   #
#               initialization. This script is automatically    #
#               called by Albator at system' startup            #
#                                                               #
# History                                                       #
# 1.01   17/05/2003 tq    Created                               #
# 2.01   10/06/2004 tq    ACD wihout HD                         #
#################################################################

##############################
# Debug and traces functions #
##############################
		
#-----------------------------------------------------------------------------
#	Function		warning
#-----------------------------------------------------------------------------
#	Meaning			Display a warning
#	Argument(s)		IN $*	String to display
#	Return Value	None
#	Functionality	Easy
#-----------------------------------------------------------------------------
warning () {
    my_date=`date +"%b %e %Y %R:%S:"`
    echo -e "$my_date [$program] $*" 1>&2 >> $dbg_file
    trace "$my_date $*"
}

#-----------------------------------------------------------------------------
#	Meaning			Display a trace
#	Argument(s)		IN $*	String to display
#	Return Value	None
#	Functionality	Easy
#-----------------------------------------------------------------------------
trace () {
    echo -e "[$program] $*"
}

#-----------------------------------------------------------------------------
#	Function		dbg_init
#-----------------------------------------------------------------------------
#	Meaning			Init the debug variable
#	Argument(s)		None
#	Return Value	None
#	Functionality	Easy
#-----------------------------------------------------------------------------
dbg_init () {
    if [ -f $dbg_on ]
    then
	debug="warning"
    else
	debug="trace"
    fi
}

write_status () {
    echo "$*" > $acd_status
}

#-----------------------------------------------------------------------------
#	Function		Error
#-----------------------------------------------------------------------------
#	Meaning			Display an Error msg
#	Argument(s)		IN $1	Flag if exit shell
#					IN $2	Error number
#					[IN $3	Parameter (depending the error)]
#	Return Value	None
#	Functionality	Easy
#-----------------------------------------------------------------------------
error () {
    case $2 in
	0) warning "Nothing to do ??" ;;
	1) warning "Invalid Option [$3]" ;;
	2) warning "No Argument for [$3]" ;;
	3) warning "Not on Main Board" ;;
	4) warning "No hard drive" ;;
	5) warning "No license" ;;
	6) warning "No Coherency [$3]" ;;
	7) warning "Not enough memory [$3]" ;;
	8) warning "Not enough memory to work with RAS [$3]" ;;
	9) warning "ACD-MLAA uses too much space on hard drive [$3]" ;;
	*) warning "Unknown Error [$2]" ;;
    esac

    if [ $1 -eq 1 ]
    then
	exit 0
    fi
}


###########################
# Constants and variables #
###########################

set_var () {
    # Physical
    if [ $HARDDRIVE -ne 0 ]
    then
	PHYSICAL_ROOT_DIR="/mnt/soft/acd"
    else
	# the /mnt/mail/acd.img loopback contains the data,
	# and is mounted on /mnt/shared/acd.
	PHYSICAL_ROOT_DIR="/mnt/shared/acd"
    fi
    ACD_DATA_LOOPBACK="/mnt/mail/acd.img"

    # Current
    CURRENT_DIR="/current/acd_mnt"
    CURRENT_WORK_DIR="/current/acd_work"
    DEFAULT_DIR="$CURRENT_DIR/default"
    CONFIG_DIR="$CURRENT_WORK_DIR/config" 
    DTD_CONFIG_FILE="$CONFIG_DIR/acd_config.dtd"
    DTD_LICENSE_FILE="$CONFIG_DIR/acd_license.dtd"
    LICENSE_FILE="$CONFIG_DIR/acd_license.xml"
    PCMAN_DIR="$CONFIG_DIR/temp"
    PCMAN_LINK="/current/acdtmp"
    
    # Current mlaa    
    MLAA_DTD_CONFIG_FILE="$CONFIG_DIR/mlaa_config.dtd"
    MLAA_DTD_LICENSE_FILE="$CONFIG_DIR/mlaa_license.dtd"
    MLAA_LICENSE_FILE="$CONFIG_DIR/mlaa_license.xml"


    # Logrotate
    LOGROTATE_FILE="/etc/logrotate.d/acd"
    LOGROTATE_CONF_FILE="/etc/logrotate_acd.conf"
    DAM_SERVICE="dam             20772/tcp"
    RHM_SERVICE="rhm             32000/tcp"
    SOAP_SERVICE="acd_soap        8082/http"

    ALBAGW="/sbin/albagw"
    dbg_file="/var/log/acd.log"
    dbg_on="/mnt/soft/acd_debug"
    acd_status="/current/acd/acd_status"
    tmp_mount="/tmp/acd_mount_dir"
    tmp_loop="/tmp/acd_loop"

    ACD_READY_FOR_CONFIG="/tmp/acd_cfg.rdy"
    NO_ERROR=0
    ERROR=1
}


##################
# Init functions #
##################

init_hosts () {

    if [ -f /tmp/hosts ]
    then
	rm /tmp/hosts
    fi
    grep amboard /etc/hosts >> /dev/null
    if [ $? -ne 0 ]
    then
	line=`grep 127.0.0.1 /etc/hosts`
	new_line=`sed -e "s/$line/$line amboard/" /etc/hosts`
	echo "$new_line" > /tmp/hosts

	cp /tmp/hosts /etc/hosts
	rm /tmp/hosts
    fi
}

init_logrotate() {
    if ! [ -f $LOGROTATE_FILE ]
    then
	ln -s $DEFAULT_DIR/config/logrotate.acd $LOGROTATE_FILE
    fi
}

clean_logrotate() {
    if [ -f $LOGROTATE_FILE ]
    then
	rm $LOGROTATE_FILE
    fi
}

init_services () {
    grep dam /etc/services >> /dev/null
    DAM=$?
    if [ $DAM -eq 1 ]
    then
    echo $DAM_SERVICE >> /etc/services
    fi
    grep rhm /etc/services >> /dev/null
    RHM=$?
    if [ $RHM -eq 1 ]
    then
    echo $RHM_SERVICE >> /etc/services
    fi
    grep acd_soap /etc/services >> /dev/null
    SOAP=$?
    if [ $SOAP -eq 1 ]
    then
    echo $SOAP_SERVICE >> /etc/services
    fi
}

init_crontab() {
#MDEGT    if [ $HARDDRIVE -eq 0 ]
#    then
	cron_file="/etc/cron"
	mercury_purge="$CURRENT_DIR/trace/mercury_purge.sh"
	chmod 500 $mercury_purge
	$debug "Add mercury_purge.sh to $cron_file"
	echo "00 02 * * * /usr/bin/nice $mercury_purge" >> $cron_file
	crontab $cron_file
#    fi
}

clean_crontab() {
#MDEGT    if [ $HARDDRIVE -eq 0 ]
#    then
	cron_file="/etc/cron"
	tmp_file="/tmp/cron"
	$debug "Clean mercury_purge.sh from $cron_file"
	cat $cron_file | sed -e "/mercury_purge/d" > $tmp_file
	mv $tmp_file $cron_file
	crontab $cron_file
#    fi
}

init_acd () {
    # add entries in /ect/services file
    init_services
    # add entry in /ect/hosts
    init_hosts
     generate_files
}


###########################
# Miscelleanous functions #
###########################

open_firewall () {
    # Activate the firewall
    /usr/bin/firewall add tel/Acd
}

close_firewall () {
    # Deactivate the firewall
    /usr/bin/firewall delete tel/Acd
}


#-----------------------------------------------------------------------------
#	Function		start_acd
#-----------------------------------------------------------------------------
#	Meaning			Start the ACD Service
#	Argument(s)		None
#	Return Value	None
#	Functionality	Easy
#-----------------------------------------------------------------------------
start_acd () {
    open_firewall
    $debug "Starting ACD engine"
    init_crontab
    init_logrotate

    $ALBAGW --cmd start ACD E ./acd_mnt/acd "/HD:$HD_FLAG /NTED /r:17" -1 "" "" "F"
    $debug "ACD engine started"
}

#-----------------------------------------------------------------------------
#	Function		stop_acd
#-----------------------------------------------------------------------------
#	Meaning			Stop the ACD Service
#	Argument(s)		None
#	Return Value	None
#	Functionality	Easy
#-----------------------------------------------------------------------------
stop_acd () {
    close_firewall
    $debug "Stopping ACD engine"
    $ALBAGW --cmd stop ACD
    clean_crontab
    clean_logrotate
    $debug "ACD engine stopped"
}


check_install_status() {

    if [ -f /test/prerequisites/boot_on_hard_disk ]
    then
	$debug "running on HD"
    else
	$debug "running on flash"
    fi
    step="reset"

    # first check the loopback
    VALID_LOOPBACK=$ERROR
    if [ -f $ACD_DATA_LOOPBACK ]
    then
	mount_loopback
	return_value=$?
	$debug "mount_loopback returned $return_value"
	if [ $return_value -eq $ERROR ]
	then
	    $debug "Error mounting loopback, suppress it!"
	    rm $ACD_DATA_LOOPBACK
	    VALID_LOOPBACK=$ERROR
	else
	    VALID_LOOPBACK=$NO_ERROR
	fi
	umount_loopback
    fi

    if [ -f $acd_status ]
    then
	grep hd_mail $acd_status >> /dev/null
	if [ $? -eq 0 ]
	then
	    # acd already installed on /mnt/mail
	    if [ $VALID_LOOPBACK = $NO_ERROR ]
	    then
		status="acd_r4_hd_mail"
	    else
		status="acd_r4_shared"
	    fi
	fi
	grep hd_shared $acd_status
	if [ $? -eq 0 ]
	then
	    # acd already installed on /mnt/shared
	    # here we have to try and migrate to /mnt/mail. The last time 
	    # it was not possible: not enough space in /mnt/mail. Try again.
	    status="acd_r4_hd_shared"
	fi
	grep flash $acd_status
	if [ $? -eq 0 ]
	then
	    # acd already installed on flash
	    # if a hd is present we will have to migrate from flash to hd.
	    status="acd_r4_flash"
	fi
    else
	# acd r3 or first install
	if [ $HARDDRIVE -eq 0 ]
	then
	    # we are on HD 
	    if [ -d /mnt/shared/acd/trace ]
	    # A r3 already ran
	    then
		# logically, it is a swap or a lola installation with restore...
		status="acd_r3"
		step="r3_to_r4_with_lola"
	    else 
		if [ $VALID_LOOPBACK = $NO_ERROR ]
		then
		    # R4 Lola installation with restore
		    # or R4 to R4 swap.
		    # should not happen
		    status="acd_r4_hd_mail"
		    step="r4_with_lola"	    
		else
		    # normal treatment
		    status="first_install"
		    step="first_install"
		fi
	    fi
	else
	    # normal treatment on flash
	    # no lola restore in this case
	    status="first_install"
	    step="first_install"	
	fi
    fi

    # check if we are performing cold/warm reset, swap...
    if [ -f /current/boot/swap_ind.par ]
    then
	# swap
	# check if there is something inside /mnt/shared/ras.
	# if yes, that means it is a swap from R3xx to R4xx,
	# otherwise /mnt/shared/acd is only a mountpoint.
	if [ $status = "acd_r3" ]
	then
	    # swap from R3 to R4, we must create the loopback,
	    # and move the data.
	    step="r3_to_r4_swap"
	else
	    # swap from R4 to R4, nothing special.
	    step="r4_to_r4_swap"
	fi	
    fi

    # reset, check if it is cold or warm
    if ! [ -f /current/boot/warm ]
    then
	reset_type="cold_reset"
    else
	reset_type="warm_reset"
    fi

    # Now check if a hard disk was added
    # it should be a warm reset.
    if [ -f /test/prerequisites/hard_disk_detected ] && \
	[ -f /test/prerequisites/boot_on_flash ] 
    then
	# a hard disk has just been plugged, all the software will
	# be automatically migrated from flash to hd, so do nothing.
	# We'll see at next reset.
	write_status "flash_migrated_to_hd"
	warning "The system will migrate the flash to hd, do nothing for the moment"
	exit 0
    else

    	if [ -f $acd_status ]
    	then
	    grep flash_migrated_to_hd $acd_status
    	fi

	if [ $? -eq 0 ]
	then
	    # The soft was migrated from flash to hd, now we have to put
	    # the right data at the right place.
	    # ie: create the new data loopback file in /mnt/mail,
	    # move the data, mount the loopback...
	    step="flash_migrated_to_hd"
	fi
    fi
    if [ -f /test/prerequisites/failsafe_mode ]
    then 
	# failsafe: ACD will be installed.
	$debug "ACD installed in failsafe mode."
	#exit 0
	step="migrated_to_flash"
    fi

    $debug "status: $status"
    $debug "step: $step"
    $debug "reset: $reset_type"
}

create_loopback() {

    if [ $HARDDRIVE -ne 0 ]
    then
         free_space=`df /mnt/mail | grep fla5 | sed -e 's+/dev/fla5[ ]*[0-9]*[ ]*[0-9]*[ ]* \(.*\)+\1+' |cut -d' ' -f1`
    else
         free_space=`df /mnt/mail | grep hda8 | sed -e 's+/dev/hda8[ ]*[0-9]*[ ]*[0-9]*[ ]* \(.*\)+\1+' |cut -d' ' -f1`
    fi

    if [ $free_space -gt 500000 ]
    then
	dd if=/dev/zero of=$ACD_DATA_LOOPBACK bs=500k count=1024
	res=$?
	if ! [ $res = 0 ]
	then
	    $warning "Error creating loopback: dd command failed"
	    return $ERROR
	fi
	mkfs.ext2 -i 4096 -b 4096 -m 5 -F -v $ACD_DATA_LOOPBACK
	res=$?
	if ! [ $res = 0 ]
	then
	    $warning "Error creating loopback: mkfs command failed"
	    return $ERROR
	fi
	# now check the loopback
	mount -o loop $ACD_DATA_LOOPBACK $tmp_loop
	res=$?
	if ! [ $res = 0 ]
	then
	    $warning "Error creating loopback: mount command failed"
	    return $ERROR
	fi
	umount $tmp_loop
    else
	# no space left, go on like this, we'll try again next time.
	$warning "Not enough space on /mnt/mail to create a loopback"
	return $ERROR
    fi
    VALID_LOOPBACK=$NO_ERROR
    return $NO_ERROR
}

migrate_data() {
    mount -o loop $ACD_DATA_LOOPBACK $tmp_loop
    mkdir $tmp_loop/config
    mkdir $tmp_loop/msg
    # look if the trace directory is in /mnt/shared.
    # this case is for lola restore.
    if [ -d /mnt/shared/acd/trace ]
    then
	    mv /mnt/shared/acd/trace $tmp_loop
    else
	mkdir $tmp_loop/trace
	cp -R $DEFAULT_DIR/trace/* $tmp_loop/trace/
    fi
    umount $tmp_loop
}

finish_data_migration() {
    mount -o loop $ACD_DATA_LOOPBACK $tmp_loop
    # look if the trace directory is in /mnt/shared.
    # this case is for lola restore.
    if [ -d /mnt/shared/acd/trace ]
    then
	    mv /mnt/shared/acd/trace $tmp_loop
    fi
    if [ -d /mnt/shared/acd/msg ]
    then
	    mv /mnt/shared/acd/msg $tmp_loop
    fi
    rm -rf /mnt/shared/acd/*
    umount $tmp_loop
}


migrate_software() {
    # check if the soft has to be migrated and if there is enough space in /mnt/mail
    # PHYSICAL_ROOT_DIR=/mnt/shared/acd
    # 1- check if the acd loopback already exists
    # 2- try and create it if necessary
    # 3- mount the loopback and migrate the soft and config.

# data:
# save/restore poste: etc, config
# lecture/ecriture PM5: config, msg
# lola: trace
    if [ $VALID_LOOPBACK = $ERROR ]
    then
	create_loopback
	return_value=$?
	$debug "create_loopback returned $return_value"
	if [ $return_value -eq $ERROR ]	
	then
	    return $ERROR
	fi
    fi

    # mount acd.img and erase all except traces and lost+found.
    mount -o loop $ACD_DATA_LOOPBACK $tmp_mount
    return_value=$?
    if [ $return_value -eq $ERROR ]	
    then
	$debug "Error mounting loopback on tmp_mount"
	rm $ACD_DATA_LOOPBACK
	return $ERROR
    fi

    for dir in `ls $tmp_mount`
    do
	if [ "$dir" != "trace" ] && [ "$dir" != "lost+found" ] && [ "$dir" != "msg" ]
	then 
	    rm -rf $tmp_mount/$dir
	fi 
    done

    case $step in
    "flash_migrated_to_hd")
	# Now check if the soft was migrated from flash
	# if hd + boot_on_hd + /mnt/soft/acd exists
	# then get config and msg back to its real place on hd: /mnt/mail
	# rq: no traces.
	if [ -f /test/prerequisites/boot_on_hard_disk ] && \
	    [ $HARDDRIVE -eq 0 ] && [ -d /mnt/soft/acd ]
	then
	    rm /mnt/soft/acd/msg/00*.wav
	    cp -R /mnt/soft/acd/* $tmp_mount/
	    rm -rf /mnt/soft/acd
	    # now duplicate the wav files for each group
	    i=2
	    j=1
	    while [ $j < 7 ]
	    do
		while [ $i < 8 ]
		do
		    cp $tmp_mount/msg/10$j.wav $tmp_mount/msg/$i0$j.wav
		    let i=i+1
		done
		let j=j+1
	    done
	fi
    ;;
    "r3_to_r4_with_lola")
	# we only have to move /mnt/shared/acd/trace 
	mv /mnt/shared/acd/trace $tmp_mount
	rm -rf $PHYSICAL_ROOT_DIR/*
    ;;
    "r3_to_r4_swap"|"r4_to_r4_swap"|"reset")
	# copy msg and traces.
	if [ -d $PHYSICAL_ROOT_DIR/msg ]
	then
	    $debug "$PHYSICAL_ROOT_DIR/msg exists, copy msg to $tmp_mount/msg"
	    rm $PHYSICAL_ROOT_DIR/msg/00*.wav
	    mv $PHYSICAL_ROOT_DIR/msg $tmp_mount
	fi
	if [ -d $PHYSICAL_ROOT_DIR/trace ]
	then
	    $debug "$PHYSICAL_ROOT_DIR/trace exists, copy trace to $tmp_mount/trace"
	    mv /mnt/shared/acd/trace $tmp_mount
	fi
	rm -rf $PHYSICAL_ROOT_DIR/*
    ;;
    *)
    esac
    umount $tmp_mount
    return $NO_ERROR
}


check_license() {
    # Software License Flags
    $ALBAGW --swl_nb acd_group 1> /dev/null 2>&1
    nb_group=$?
    $ALBAGW --swl_nb acd_agent 1> /dev/null 2>&1
    nb_active_agents=$?
    $ALBAGW --swl_nb acd_dam 1> /dev/null 2>&1
    nb_active_dam=$?
    $ALBAGW --swl_nb acd_supervisor 1> /dev/null 2>&1
    nb_active_supervisor=$?
    $ALBAGW --swl rcm 1> /dev/null 2>&1
    active_rcm=$?
    $ALBAGW --swl acd_statistic_allow 1> /dev/null 2>&1
    active_statistics=$?
    echo "*-------------------*"
    echo "ACD software licenses"
    echo "*-------------------*"
    echo "ACD groups: $nb_group"
    echo "Active ACD agents: $nb_active_agents"
    echo "Active ACD Agents Assistant applications: $nb_active_dam"
    echo "Active ACD Supervisor Console applications: $nb_active_supervisor"

# @BD@OXO_10.0@crqms00043364@140512@verohit@ #
#   if [ $active_statistics -eq 0 ] && [ $HARDDRIVE -eq 0 ]
# @ED@OXO_10.0@crqms00043364@140512@verohit@ #
# @BA@OXO_10.0@crqms00043364@140512@verohit@ #
	if [ $active_statistics -eq 0 ] && ([ $HARDDRIVE -eq 0 ]  || [ $POWERCPUEE -eq 0 ])
# @EA@OXO_10.0@crqms00043364@140512@verohit@ #
    then
     	statistic="yes"
        echo "ACD Statistics: Enabled"
    fi

    acd_license="yes"
    #if [ $nb_group -ne 0 ] && [ $nb_active_agents -eq 0 ] && [ $nb_active_dam -eq 0 ] && [ $nb_active_supervisor -eq 0 ] && [ $statistic = "no" ] 
    #8-03-13 if [ $nb_group -ne 0 ] && [ $nb_active_agents -eq 0 ] && [ $nb_active_dam -eq 0 ] && [ $nb_active_supervisor -eq 0 ] 
	if [ $nb_group -eq 0 ] && [ $nb_active_agents -eq 0 ] && [ $nb_active_dam -eq 0 ] && [ $nb_active_supervisor -eq 0 ] 
    then
	acd_license="no"
    fi
    rcm_license="no"
    if [ $acd_license = "no" ] && [ $active_rcm -eq 0 ] 
    then

	if [ $nb_group -ne 0 ] && [ $nb_active_agents -eq 0 ]
	then
	  rcm_license="yes"
	fi
    fi
    
    if [ $acd_license = "yes" ] && [ $active_rcm -eq 0 ] 
    then
	rcm_license="yes" 
    fi
	
    # mlaa License Flags
    echo ""
    echo "MLAA software licenses"
    echo "*--------------------*"

    $ALBAGW --swl_nb acd_eaa 1> /dev/null 2>&1
    nb_eaa=$?

    echo "Number of trees: $nb_eaa"
    echo ""

    if [ $nb_eaa -ne 0 ] 
    then
	mlaa_license="yes"
    fi

    $debug "acd_license= $acd_license ; acd_statistics= $statistic"
    $debug "mlaa_license= $mlaa_license"    
    $debug "rcm_license= $rcm_license ; rcm[nb_grp=$nb_group ; nb_agt=$nb_active_agents]" 

  
    #1
    if [ $acd_license = "no" ] && [ $mlaa_license = "no" ] && [ $rcm_license = "no" ] 
    then
	if [ -d $CONFIG_DIR ]
	then
	    #delete xml files:acd_license.xml, acd_license.dtd, acd_config.xml
	    #acd_config.dtd, mlaa_license.xml, mlaa_license.dtd, mlaa_config.xml, mlaa_config.dtd
	    r\m -Rf $CONFIG_DIR/*
	fi
	error 1 5
    fi

    #2
   #MDEGT 08/09 must run on flash if [ $acd_license = "no" ] && [ $mlaa_license = "yes" ] && [ $mlaa_service = "yes" ]
   if [ $acd_license = "no" ] && [ $mlaa_license = "yes" ]
   then
     ###OXO 9.0 - RCM
       if [ -d $CONFIG_DIR ]
       then
       #delete xml files:acd_license.xml, acd_license.dtd, acd_config.xml
          if [ $rcm_license = "no" ]
          then
             r\m -Rf $CONFIG_DIR/acd_*
             r\m -Rf $CONFIG_DIR/rcm_directory.xml
          fi
       fi
   fi    
   #3
    #MDEGT 08/09 run on flash if [ $acd_license = "yes" ] && [ $mlaa_license = "no" ] && [ $mlaa_service = "no" ] 
    if [ $acd_license = "yes" ] && [ $mlaa_license = "no" ]
    then
	if [ -d $CONFIG_DIR ]
	then
	    #delete mlaa_license.xml, mlaa_license.dtd, mlaa_config.xml, mlaa_config.dtd
	    r\m -Rf $CONFIG_DIR/mlaa_*
	fi
    fi
}

create_license() {

    #Header
    echo "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\" ?>" > $LICENSE_FILE
    echo "<!DOCTYPE ACD_LICENSE SYSTEM \"acd_license.dtd\">" >> $LICENSE_FILE
    echo "<ACD_LICENSE VERSION=\"1.0\">" >> $LICENSE_FILE
    echo "<ACD_LICENSE_LIST>" >> $LICENSE_FILE
    echo "  <LICENSE name=\"nb_group\">$nb_group</LICENSE>" >> $LICENSE_FILE
    echo "  <LICENSE name=\"nb_active_agents\">$nb_active_agents</LICENSE>" >> $LICENSE_FILE
    echo "  <LICENSE name=\"nb_active_dam\">$nb_active_dam</LICENSE>" >> $LICENSE_FILE
    echo "  <LICENSE name=\"nb_active_supervisor\">$nb_active_supervisor</LICENSE>" >> $LICENSE_FILE
    echo "  <LICENSE name=\"statistic\">$statistic</LICENSE>" >> $LICENSE_FILE
    ###############  OXO 9.0 - RCM  ###############################
    echo "  <LICENSE name=\"rcm\">$rcm_license</LICENSE>" >> $LICENSE_FILE
    ###############################################################
    echo "</ACD_LICENSE_LIST>" >> $LICENSE_FILE
    echo "</ACD_LICENSE>" >> $LICENSE_FILE
}

create_mlaa_license() {

    #Header
    echo "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\" ?>" > $MLAA_LICENSE_FILE
    echo "<!DOCTYPE MLAA_LICENSE SYSTEM \"mlaa_license.dtd\">" >> $MLAA_LICENSE_FILE
    echo "<MLAA_LICENSE VERSION=\"1.0\">" >> $MLAA_LICENSE_FILE
    echo "<MLAA_LICENSE_LIST>" >> $MLAA_LICENSE_FILE
    echo "  <LICENSE name=\"nb_arbre\">$nb_eaa</LICENSE>" >> $MLAA_LICENSE_FILE
    echo "</MLAA_LICENSE_LIST>" >> $MLAA_LICENSE_FILE
    echo "</MLAA_LICENSE>" >> $MLAA_LICENSE_FILE
}

get_operator() {
    if ! [ -f /tmp/operator ]; then
	OPERATOR="AA"
    else
	OPERATOR=`cat /tmp/operator`
    fi
}

check_memory() {
    $ALBAGW --swl_nb ras 1> /dev/null 2>&1
    nb_ras=$?
    mem=`grep MemTotal: /proc/meminfo |cut -d ':' -f 2 |cut -d 'k' -f 1`
    ram=`expr $mem / 976.56`
    # 1000000 / 1024 = 976.56
    if [ $ram -lt 64 ]
    then
	error 0 7 $ram
    fi
    if [ $ram -eq 64 ]
    then
	if [ $nb_ras -ne 0 ]
	then
	    error 0 8 $ram
	fi
    fi
}

check_harddrive() {
    space_used=`du -s $PHYSICAL_ROOT_DIR | sort -n |cut -f 1`
    if [ $space_used -gt 500000 ] 
    then
	error 0 9 $space_used
    fi
}


##########################
# Installation functions #
##########################

make_dir () {
    # pre-processing for init
    # should only be useful on cold reset
    if ! [ -d $PHYSICAL_ROOT_DIR ] 
    then
	mkdir -p $PHYSICAL_ROOT_DIR
    fi
    if ! [ -d $CURRENT_WORK_DIR ]
    then
	ln -s $PHYSICAL_ROOT_DIR $CURRENT_WORK_DIR
    fi

    if ! [ -d $CONFIG_DIR ]
    then
	mkdir -p $PHYSICAL_ROOT_DIR/config
    fi

    if ! [ -d $PCMAN_DIR ]
    then
	mkdir -p $PCMAN_DIR
    fi

    if ! [ -d $PCMAN_LINK ]
    then
    	ln -fs $PCMAN_DIR $PCMAN_LINK
    fi
}
generate_acd_dtd_files () {
    if ! [ -f $DTD_CONFIG_FILE ] 
    then
	echo > "$CONFIG_DIR/acd_config.dtd"
#	cp  $DEFAULT_DIR/config/acd_config.dtd $CONFIG_DIR
    fi

    if ! [ -f $DTD_LICENSE_FILE ] 
    then
	cp  $DEFAULT_DIR/config/acd_license.dtd $DTD_LICENSE_FILE
    fi

}

generate_mlaa_dtd_files () {
    if ! [ -f $MLAA_DTD_CONFIG_FILE ] 
    then
#	cp  $DEFAULT_DIR/config/mlaa_config.dtd $CONFIG_DIR
	cp  $DEFAULT_DIR/config/directory.dtd $CONFIG_DIR
	cp  $DEFAULT_DIR/config/messages.dtd   $CONFIG_DIR
	echo > "$CONFIG_DIR/mlaa_config.dtd"
    fi

    if ! [ -f $MLAA_DTD_LICENSE_FILE ] 
    then
	cp  $DEFAULT_DIR/config/mlaa_license.dtd $MLAA_DTD_LICENSE_FILE
    fi
}

generate_files () {

    if [ $acd_license = "yes" ] || [ $rcm_license = "yes" ]
    then
        create_license
        generate_acd_dtd_files
    fi

    if [ $acd_license = "no" ] || [ $rcm_license = "yes" ]
    then
        create_license
        generate_acd_dtd_files
    fi

    if [ $mlaa_license = "yes" ]
    then
        create_mlaa_license
        generate_mlaa_dtd_files
    fi
}

init_files () {

    if ! [ -d $CURRENT_DIR/etc ]
    then
	$debug "using default etc"
	mkdir $PHYSICAL_ROOT_DIR/etc
# We want to preserve webadmin rights ...
	cp -a $DEFAULT_DIR/etc/* $CURRENT_DIR/etc
    else
	# Backward compatibilty checks
	PUT_FILE="$CURRENT_DIR/etc/client/arbre.maa"
	[ -f $PUT_FILE ] || touch $PUT_FILE
#MDEGT added 14-08-09
        chown root:webadmin $CURRENT_DIR/etc/client
#end added
	chown webadmin:webadmin $PUT_FILE
#seems not working with chmod on OXO_R8.0	chmod g+w $PUT_FILE
#MDEGT added 14-08-09
#MDEGT 30/06/2011	chmod 751 $PUT_FILE
#end added
    fi
    if ! [ -d $CURRENT_DIR/msg ]
    then
	$debug "using default msg"
	mkdir $PHYSICAL_ROOT_DIR/msg
	cp -R $DEFAULT_DIR/msg/* $CURRENT_DIR/msg
	chmod 444 $CURRENT_DIR/msg/*
    fi

#MDEGT    if ! [ -d $CURRENT_DIR/trace ] && [ $HARDDRIVE -eq 0 ]
    if ! [ -d $CURRENT_DIR/trace ] 
    then
	$debug "using default trace"
	mkdir $PHYSICAL_ROOT_DIR/trace
	cp -R $DEFAULT_DIR/trace/* $CURRENT_DIR/trace/
    fi

# @BD@OXO_10.0@crqms00000349@140512@verohit@ #
#    if [ $HARDDRIVE -eq 0 ]
# @ED@OXO_10.0@crqms00000349@140512@verohit@ #
# @BA@OXO_10.0@crqms00000349@140512@verohit@ #
    if [ $HARDDRIVE -eq 0 ] || [ $POWERCPUEE -eq 0 ]
# @EA@OXO_10.0@crqms00000349@140512@verohit@ #
    then
	touch $CURRENT_DIR/xerces.log
    fi

    chown ssmgr.ssmgr $CONFIG_DIR/.
    chmod g+w $CONFIG_DIR/.
    chown ssmgr.ssmgr $PCMAN_DIR
    chmod a+w $PCMAN_DIR

    cp $DEFAULT_DIR/msg/* $CURRENT_DIR/msg/
    chmod 444 $CURRENT_DIR/msg/*
    if [ -f /tmp/mulaw_ACD ]
    then
	MULAW=`cat /tmp/mulaw_ACD`
	if [ $MULAW = "1" ]
	then
	    ln -fs $CURRENT_DIR/msg/001_Mulaw.wav $CURRENT_DIR/msg/001.wav
	    ln -fs $CURRENT_DIR/msg/002_Mulaw.wav $CURRENT_DIR/msg/002.wav
	else
	    ln -fs $CURRENT_DIR/msg/001_Alaw.wav $CURRENT_DIR/msg/001.wav
	    ln -fs $CURRENT_DIR/msg/002_Alaw.wav $CURRENT_DIR/msg/002.wav
	fi
    else
	$debug "no /tmp/mulaw file! Using Alaw"
	ln -fs $CURRENT_DIR/msg/001_Alaw.wav $CURRENT_DIR/msg/001.wav
	ln -fs $CURRENT_DIR/msg/002_Alaw.wav $CURRENT_DIR/msg/002.wav
    fi

}

umount_loopback () {

    umount $ACD_DATA_LOOPBACK
}

mount_loopback () {

    mount | grep "$ACD_DATA_LOOPBACK on $PHYSICAL_ROOT_DIR"
    res=$?
    if [ $res = 0 ]
    then
	$debug "Already mounted"
	return $NO_ERROR
    fi

    $debug "mounting loopback"
    if ! [ -d $PHYSICAL_ROOT_DIR ]
    then
	mkdir $PHYSICAL_ROOT_DIR
    fi
    mount -o loop $ACD_DATA_LOOPBACK $PHYSICAL_ROOT_DIR
    res=$?
    if ! [ $res = 0 ]
    then
	$warning "Error mounting loopback: mount command failed"
	rm -rf $ACD_DATA_LOOPBACK
	return $ERROR
    fi
    return $NO_ERROR
}

clean_data () {

    $debug "A swap is ongoing, erasing all except trace and vocal messages"
    for dir in `ls $PHYSICAL_ROOT_DIR`
    do
	if [ "$dir" != "msg" ] && [ "$dir" != "trace" ] && [ "$dir" != "lost+found" ]
	then 
	    rm -rf $PHYSICAL_ROOT_DIR/$dir
	fi 
    done
    rm $CURRENT_DIR/msg/001*.wav
    rm $CURRENT_DIR/msg/002*.wav
}

#-----------------------------------------------------------------------------
#	Function		install_acd
#-----------------------------------------------------------------------------
#	Meaning			Install the ACD Service
#	Argument(s)		None
#	Return Value	None
#	Functionality	Launched at each startup of the system, this
#                       function determines if we are making a 
#                       - swap: erase all except trace and msg, then install the new soft.
#                       - cold reset: remove acd_config.xml file.
#                       - cold reset: remove mlaa_config.xml file.
#                       - warm reset: nothing to do.
#-----------------------------------------------------------------------------
install_acd () {

    # first check what have to be created, then migrated, then reset.
    check_install_status

    if [ -f $acd_status ]
    then
  	rm $acd_status
    fi

    if [ -d /mnt/shared/acd/trace ] && [ $VALID_LOOPBACK = $NO_ERROR ] 
    then
	$debug "ACD loopback exists, but there still remain some traces to migrate."
	finish_data_migration
    fi

    case $step in
	"first_install")
	    if [ $HARDDRIVE -ne 0 ]
	    then
		# we are running on flash! PHYSICAL_ROOT_DIR="/mnt/soft/acd"
		$debug "$step on flash" 
	    else
		if [ $VALID_LOOPBACK = $ERROR ]
		then
		    $debug "creating loopback"
		    create_loopback
		    return_value=$?
		    $debug "create_loopback returned $return_value"
		    if [ $return_value -eq $ERROR ]
		    then
			write_status "hd_shared"
		    else
			migrate_data
			mount_loopback
			return_value=$?
			$debug "mount_loopback returned $return_value"
			if [ $return_value -eq $ERROR ]	
			then
			    VALID_LOOPBACK=$ERROR
			    write_status "hd_shared"
			else
			    write_status "hd_mail"
			fi
		    fi
		else
		    $debug "loopback exists"
		    mount_loopback
		    return_value=$?
		    $debug "mount_loopback returned $return_value"
		    if [ $return_value -eq $ERROR ]	
		    then
			VALID_LOOPBACK=$ERROR
			write_status "hd_shared"
		    else
			write_status "hd_mail"
		    fi
		fi
	    fi
	;;
	"r4_with_lola")
	    # Clean the loopback
	    mount_loopback
	    return_value=$?
	    $debug "mount_loopback returned $return_value"
	    if [ $return_value -eq $ERROR ]	
	    then
		VALID_LOOPBACK=$ERROR
		write_status "hd_shared"
	    else
		write_status "hd_mail"
	    fi
	    for dir in `ls $PHYSICAL_ROOT_DIR`
	    do
		if [ "$dir" != "trace" ] && [ "$dir" != "lost+found" ]
		then 
		    rm -rf $PHYSICAL_ROOT_DIR/$dir
		fi 
	    done
	;;
	"r3_to_r4_swap"|"r3_to_r4_with_lola")
	    if [ $HARDDRIVE -ne 0 ]
	    then
		# we are running on flash! PHYSICAL_ROOT_DIR="/mnt/soft/acd"
		$debug "$step on flash"
		clean_data
	    else
		migrate_software
		return_value=$?
		$debug "migrate_software returned $return_value"
		if [ $return_value -eq $ERROR ]
		then
		    write_status "hd_shared"
		else
		    mount_loopback
		    write_status "hd_mail"
		fi
		clean_data
	    fi
	;;
	"r4_to_r4_swap"|"reset")
	    if [ $HARDDRIVE -ne 0 ]
	    then
		# we are running on flash! PHYSICAL_ROOT_DIR="/mnt/soft/acd"
		$debug "$step on flash"
 # Clean the loopback
	    mount_loopback
	    return_value=$?
	    $debug "mount_loopback returned $return_value"
	    if [ $return_value -eq $ERROR ]	
	    then
		VALID_LOOPBACK=$ERROR
	    fi 
	    else
		if [ $status = "acd_r4_hd_shared" ] 
		then
		    # soft still in /mnt/shared!!!, try to migrate it
		    migrate_software
		    return_value=$?
		    $debug "migrate_software returned $return_value"
		    if [ $return_value -eq $ERROR ]
		    then
			write_status "hd_shared"
		    else
			mount_loopback
			write_status "hd_mail"
		    fi
		else
		    if [ $status = "acd_r4_hd_mail" ] 
		    then
			mount_loopback
			write_status "hd_mail"
		    fi
		fi
	    fi
	;;
        "migrated_to_flash")
        #Taking ACD backup for failsafe mode
            if [ $HARDDRIVE -ne 0 ]
            then
                $debug "$step on failsafe mode"
            fi
        ;;
	"flash_migrated_to_hd")
	# a bit more difficult, data have been migrated from /mnt/flash/acd to /mnt/hd/acd.
	# we have to move it to /mnt/mail/acd.img
	    migrate_software
	    return_value=$?
	    $debug "migrate_software returned $return_value"
	    if [ $return_value -eq $ERROR ]
	    then
		# problem, we have to migrate data to /mnt/shared !!!
		rm /mnt/soft/acd/msg/00*.wav
		mv /mnt/soft/acd /mnt/shared/
		# now duplicate the wav files for each group
		i=2
		j=1
		while [ $j < 7 ]
		do
		    while [ $i < 8 ]
		    do
			cp /mnt/shared/acd/msg/10$j.wav /mnt/shared/acd/msg/$i0$j.wav
			let i=i+1
		    done
		    let j=j+1
		done    
		write_status "hd_shared"
	    else
		mount_loopback
		write_status "hd_mail"
	    fi
	;;
	*)
    esac

    if [ $step = "r4_to_r4_swap" ]
    then
	clean_data
    fi

    if ! [ -d $CURRENT_WORK_DIR ]
    then
	ln -s $PHYSICAL_ROOT_DIR $CURRENT_WORK_DIR
    fi

    case $reset_type in
	"cold_reset")
	    $debug "suppressing config"
	    if [ -d $CONFIG_DIR ]
	    then
            #delete xml files:acd_license.xml, acd_license.dtd, acd_config.xml
            #acd_config.dtd, mlaa_license.xml, mlaa_license.dtd, mlaa_config.xml,mlaa_config.dtd
		r\m -rf $CONFIG_DIR/*

	        if [ -d $PCMAN_LINK ]
                then
	           r\m -rf $PCMAN_LINK
            	fi
	
	    fi
	;;
	"warm_reset")
	    $debug "warm reset, nothing to do"
	;;
	*)
    esac

    if [ $HARDDRIVE -ne 0 ]
    then
	# we are running on flash! PHYSICAL_ROOT_DIR="/mnt/soft/acd"
	$debug "$step on flash" 
	write_status "flash"
    fi

    # create dir if necessary
    make_dir
    init_files

    # The ACD config path are present
    # lpcm (cminiti) waits for this file to start
    # the restore.
    touch $ACD_READY_FOR_CONFIG
}


#-----------------------------------------------------------------------------
#	Function		Main
#-----------------------------------------------------------------------------
#	Meaning			Easy
#	Argument(s)		None
#	Return Value	None
#	Functionality	Easy
#-----------------------------------------------------------------------------
program="ACD_INI"

#mlaa_service="no"
mlaa_license="no"
acd_license="no"
hard_present="no"
rcm_license="no"
statistic="no"

# @BA@OXO_10.0@crqms00043364@140512@verohit@ #
POWERCPUEE_ANV="3EH73084AL"
eval `cat /proc/alize/cpuconf | grep "^ANV"`
if echo "$ANV" | grep -q "$POWERCPUEE_ANV" ; then
POWERCPUEE=0
else
POWERCPUEE=1
fi
# @EA@OXO_10.0@crqms00043364@140512@verohit@ #

# Board Flags
# useless as this script is started by Albator only on Main board.
alzcheck --main 1> /dev/null 2>&1
CPU_MAIN=$?

# Is a hard disk present?
alzcheck --harddrive 1> /dev/null 2>&1
HARDDRIVE=$?

set_var
touch $dbg_on
dbg_init
if [ $CPU_MAIN -ne 0 ]
then
    error 1 3
fi

# HD Mandatory for MLAA but not for ACD
HD_FLAG=1 #MLAA works without HD since OXO 8.0
if [ $HARDDRIVE -ne 0 ]
then
#MDEGT    HD_FLAG=0
 HD_FLAG=1
    error 0 4
fi

case $1 in
    install)
	mkdir $tmp_loop
	mkdir $tmp_mount
	install_acd
	check_license
	init_acd
	start_acd
	rmdir $tmp_loop
	rmdir $tmp_mount
	exit 0
    ;;
    start)
	check_license
	start_acd
	exit 0
    ;;
    stop)
	stop_acd
	exit 0
    ;;
    restart)
	stop_acd
	sleep 5
	check_license
	start_acd
	exit 0
    ;;
    don)
	touch $dbg_on
	exit 0
    ;;
    doff)
	rm $dbg_on
	exit 0
    ;;
    license)
	create_license
	create_mlaa_license
	exit 0
    ;;
    check_mem)
	check_memory
	exit 0
    ;;
    check_hd)
	check_harddrive
	exit 0
    ;;
    init_cron)
	init_crontab
	exit 0
    ;;
    clean_cron)
	clean_crontab
	exit 0
    ;;
    init_log)
	init_logrotate
	exit 0
    ;;
    clean_log)
	clean_logrotate
	exit 0
    ;;
    warning)
	warning "test warning: $2"
	exit 0
    ;;
    error)
	error 0 5
	exit 0
    ;;
    check_status)
	check_install_status
	exit 0
    ;;
    check_license)
	check_license
	exit 0
    ;;
     *)
esac
$debug "Bad or no parameter!!!"
exit 0




