#!/bin/bash
#
#
#*****************SynAST Package Installation/Removal Script.*****************
#Copyright	(c) 2008, SynAST Inc.
#Written by Xiong ce <liny@sanhuid.com>
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version
#2 of the License, or (at your option) any later version.
#

VERSIONS=Ver1.6.0.0

TEJ21SET=0
TEJ84SET=0
TEJASET=0

banner()
{
	echo -e "\t----------------------------------------------------------"
	echo -e "\t          SynAST $VERSIONS Installation Script"
	echo -e "\t----------------------------------------------------------"
	echo ""
	return 0
}

function card_list_clear ()
{
	clear
	echo "Card Type:Serialno" | awk -F: '{printf "\t%-20s\t\t%-20s\n", $1,$2}'
	cat /tmp/synast_cardlist | while read clline
	do
		echo $clline | awk -F: '{printf "\t%-20s\t\t%-20s\n", $1,$2}'
	done
}

function card_list_conf ()
{
	if [ -f /tmp/synast_cardlist ]; then
		rm -rf /tmp/synast_cardlist
	fi
	drlist="fxm8apci fxm16apcie fxm32 tejxapci tej21 tej84"
	for dr in $drlist
	do
		if [ -f /sys/module/$dr/parameters/card_list_order ]; then
			cardlist=`cat /sys/module/$dr/parameters/card_list_order`
		elif [ -f /sys/module/$dr/card_list_order ]; then
			cardlist=`cat /sys/module/$dr/card_list_order`
		else
			continue
		fi
		OLDIFS="$IFS"
		IFS=","
		for cardSerialno in $cardlist
		do
			echo "$dr:$cardSerialno" >> /tmp/synast_cardlist
		done
		IFS="$OLDIFS"
	done
	
	for dr in $drlist
	do
		cardnums=`cat /tmp/synast_cardlist | grep "^$dr:" | sed -n '$='`
		if [ -z "$cardnums" ]; then
			continue
		fi
		if [ $cardnums -lt 2 ]; then
			continue
		fi
		adjustcardlist="$adjustcardlist $dr"
	done
	
	card_list_clear
	echo -n "Adjust Card Type [$adjustcardlist] (q) : "
	read adjustct
	while [ $adjustct != "q" ];do
		for tmpadjustct in $adjustcardlist
		do
			if [ $adjustct = $tmpadjustct ];then
				rmmod $adjustct
				card_list_clear
				echo -n "Adjust Card Order (Comma separated): "
				read ajustco
				modprobe $adjustct card_list_order=$ajustco
				
				sed '/$adjustct/d' /tmp/synast_cardlist > /tmp/synast_cardlist
				if [ -f /sys/module/$adjustct/parameters/card_list_order ]; then
					cardlist=`cat /sys/module/$adjustct/parameters/card_list_order`
				elif [ -f /sys/module/$adjustct/card_list_order ]; then
					cardlist=`cat /sys/module/$adjustct/card_list_order`
				else
					continue
				fi
				OLDIFS="$IFS"
				IFS=","
				for cardSerialno in $cardlist
				do
					echo "$adjustct:$cardSerialno" >> /tmp/synast_cardlist
				done
				IFS="$OLDIFS"
			fi
		done
		
		card_list_clear
		echo -n "Adjust Card Type [$adjustcardlist] (q) : "
		read adjustct
	done

}

unload_module() {
        module="$1"
        line=`lsmod 2>/dev/null | grep "^$1 "`
        if [ "$line" = '' ]; then return; fi # module was not loaded

        set -- $line
        # $1: the original module, $2: size, $3: refcount, $4: deps list
        mods=`echo $4 | tr , ' '`
        # xpp_usb keeps the xpds below busy if an xpp hardware is
        # connected. Hence must be removed before them:
        case "$module" in xpd_*) mods="xpp_usb $mods";; esac
        for mod in $mods; do
                # run in a subshell, so it won't step over our vars:
                (unload_module $mod)
                # TODO: the following is probably the error handling we want:
                # if [ $? != 0 ]; then return 1; fi
        done
        rmmod $module
}


function dahddiff ()
{
	driver_list="fxm8apci fxm16apcie fxm32 tejxapci tej21 tej84"
	
	if [ $DAHDIVERSION -ne 1 ]; then
		return 0;
	fi
	
	for drivern in $driver_list
	do
			mv $DAHDI_SOURCE_DIR/$drivern/Kbuild $DAHDI_SOURCE_DIR/$drivern/Kbuild.synbak
			sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DDAHDI22' $DAHDI_SOURCE_DIR/$drivern/Kbuild.synbak > $DAHDI_SOURCE_DIR/$drivern/Kbuild
	done

	return 0
}

function seltejamode ()
{
	if [ $TEJASET != "0" ];then
		return 0
	fi
	TEJASET=1
	
	echo -n "SELECT TEJA MODE [t, e, j] : "
	read response

	mv $DAHDI_SOURCE_DIR/tejxapci/Kbuild $DAHDI_SOURCE_DIR/tejxapci/Kbuild.synbak
	if [ $response = "t" ]; then
		sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DT1MODE' $DAHDI_SOURCE_DIR/tejxapci/Kbuild.synbak > $DAHDI_SOURCE_DIR/tejxapci/Kbuild
	elif [ $response = "j" ]; then
		sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DJ1MODE' $DAHDI_SOURCE_DIR/tejxapci/Kbuild.synbak > $DAHDI_SOURCE_DIR/tejxapci/Kbuild
	else
		echo -n "SELECT TEJA [75, 120]ohm : "
		read vohm
		if [ $vohm = "75" ]; then
		    sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DE1MODE -DE75OHM' $DAHDI_SOURCE_DIR/tejxapci/Kbuild.synbak > $DAHDI_SOURCE_DIR/tejxapci/Kbuild
		else
		    sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DE1MODE' $DAHDI_SOURCE_DIR/tejxapci/Kbuild.synbak > $DAHDI_SOURCE_DIR/tejxapci/Kbuild
		fi
	fi

	return 0
}

function seltejbmode ()
{
	if [ $1 = "tej21" ];then
		if [ $TEJ21SET != "0" ];then
			return 0
		fi
		TEJ21SET=1
	fi
	
	if [ $1 = "tej84" ];then
		if [ $TEJ84SET != "0" ];then
			return 0
		fi
		TEJ84SET=1
	fi
	
	
	echo -n "select $1 mode [t, e, j] : "
	read response
	
	mv $DAHDI_SOURCE_DIR/$1/Kbuild $DAHDI_SOURCE_DIR/$1/Kbuild.synbak
	if [ $response = "t" ]; then
		sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DT1MODE' $DAHDI_SOURCE_DIR/$1/Kbuild.synbak > $DAHDI_SOURCE_DIR/$1/Kbuild
	elif [ $response = "j" ]; then
		sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DJ1MODE' $DAHDI_SOURCE_DIR/$1/Kbuild.synbak > $DAHDI_SOURCE_DIR/$1/Kbuild
	else
		echo -n "select [75, 120]ohm : "
		read vohm
		if [ $vohm = "75" ]; then
			sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DE1MODE -DE75OHM' $DAHDI_SOURCE_DIR/$1/Kbuild.synbak > $DAHDI_SOURCE_DIR/$1/Kbuild
		else
			sed '/EXTRA_CFLAGS/a EXTRA_CFLAGS+= -DE1MODE' $DAHDI_SOURCE_DIR/$1/Kbuild.synbak > $DAHDI_SOURCE_DIR/$1/Kbuild
		fi
	fi

	return 0
}

function find_dahdi_tools()
{
	echo -n "Please enter dahdi_tools source directory [q](exit install):"
	read dahdi_tool

	if [ $dahdi_tool = "q" ]; then
		return 1
	fi
	
	if [ ! -d $dahdi_tool ]; then 
		echo "Invalid dahdi_tools $dahdi_tool"
		find_dahdi_tools
	else
		if [ ! -f $dahdi_tool/.version ]; then
			echo "Error: .version not found in $dahdi_tool"
			find_dahdi_tools
		else
			DAHDI_TOOLS_DIR=$dahdi_tool
			DTVER=`cat $DAHDI_TOOLS_DIR/.version`
		fi
	fi

	return 0
}

function find_dahdi_dirs ()
{
	echo -n "Please enter working dahdi directory [q](exit install) : "
	read response
	
	if [ $response = "q" ]; then
		return 1
	fi
	
	if [ ! -d $response ]; then 
		echo "Invalid Response $response"
		find_dahdi_dirs
	else
		DAHDI_SOURCE_DIR=$response
		
		#Check is dahdi complete version
		if [ ! -d $DAHDI_SOURCE_DIR/linux ]; then 
			DAHDI_INSTALL_DIR=$DAHDI_SOURCE_DIR
			DAHDI_SOURCE_DIR=$DAHDI_SOURCE_DIR/drivers/dahdi
			DLVER=`cat $DAHDI_INSTALL_DIR/.version`
			find_dahdi_tools || return 0
		else
			DAHDI_INSTALL_DIR=$DAHDI_SOURCE_DIR
			DAHDI_SOURCE_DIR=$DAHDI_SOURCE_DIR/linux/drivers/dahdi
			
			DLVER=`cat $DAHDI_INSTALL_DIR/linux/.version`
			DTVER=`cat $DAHDI_INSTALL_DIR/tools/.version`
		fi
		
		if [[ $DLVER == 2.2.* ]]; then
			DAHDIVERSION=1
		else
			DAHDIVERSION=2
		fi
		
		if [ ! -f $DAHDI_SOURCE_DIR/Kbuild ]; then
		clear
		echo
		echo "Error: uncorrect driver directory"
		echo
		find_dahdi_dirs
		fi
	fi
	return 0
}

prompt()
{
	echo -ne "$*" >&2
	read CMD rest
	return 0
}

getyn()
{
	while prompt "$* (y/n) "
	do	case $CMD in
			[yY])	return 0
				;;
			[nN])	return 1
				;;
			*)	echo -e "\nPlease answer y or n" >&2
				;;
		esac
	done
}

Install()
{
	banner
	echo "Install SynAST AST package now!"
	getyn "Would you like to install SynAST AST package now?" || return 0
	
	find_dahdi_dirs || return 0
	
	if [ ! -f $DAHDI_INSTALL_DIR/Makefile ] && [ ! -f $DAHDI_INSTALL_DIR/Makefile.synbak ]; then
		echo
		echo "Error: Makefile not found in $DAHDI_INSTALL_DIR"
		echo
		return 0
	fi
	
	unload_module zaptel
	unload_module dahdi
		
	driver_dir_list="fxm8apci fxm16apcie fxm32 tejxapci tej21 tej84 cdcx522apci"
	package_dir_list="src/fxm/fxm8apci src/fxm/fxm16apcie src/fxm/fxm32 src/tej/tejxapci src/tej/tej21 src/tej/tej84 src/cdc/cdcx522apci"

	mv $DAHDI_SOURCE_DIR/Kbuild $DAHDI_SOURCE_DIR/Kbuild.synbak
	sed "/xpp/a obj-m += fxm8apci/\nobj-m += fxm16apcie/\nobj-m += fxm32/\nobj-m += cdcx522apci/\nobj-m += tejxapci/\nobj-m += tej21/\nobj-m += tej84/" $DAHDI_SOURCE_DIR/Kbuild.synbak > $DAHDI_SOURCE_DIR/Kbuild	
	
	for dir_name in $driver_dir_list
	do
		rm -rf $DAHDI_SOURCE_DIR/$dir_name
	done

	for dir_name in $package_dir_list
	do
			cp -ar $dir_name $DAHDI_SOURCE_DIR
	done
	
	cp SynAST_driver_init /usr/sbin/SynAST_driver_init
	chmod 711 /usr/sbin/SynAST_driver_init
	
	sed '/SynAST_driver_init/d' /etc/rc.local > /tmp/rc.local.tmp
	mv /tmp/rc.local.tmp /etc/rc.local
	echo SynAST_driver_init >> /etc/rc.local
	chmod 755 /etc/rc.local
	
	sed '/SynAST_driver_init/d' /etc/rc.d/rc.local > /tmp/rc.local.tmp
	mv /tmp/rc.local.tmp /etc/rc.d/rc.local
	echo SynAST_driver_init >> /etc/rc.d/rc.local
	chmod 755 /etc/rc.d/rc.local
	
	cp astcfg_dahdi /usr/sbin/astcfg_dahdi
	chmod 711 /usr/sbin/astcfg_dahdi

	lsmodlist=`lsmod |grep dahdi`
	
	for dir_name in $driver_dir_list
	do
			echo $lsmodlist|grep $dir_name >/dev/null
			if [ $? = 0 ]; then	
				rmmod $dir_name
			fi
	done
	
	dahddiff
	
	listn="0 1 2 3 4 5 6 7 8 9 a b c d e f"
	devno=0
	for devno in $listn
	do
		str=`lspci | grep "rev 0b" | grep 00f$devno`
		if [ -z "$str" ]; then
		tmpp=0
		else
			case $devno in
					[1-2,4-5]) seltejbmode tej21;;
					[a-c]) seltejamode;;
			esac
		fi
		
		str=`lspci | grep "rev 0b" | grep 00e$devno`
		if [ -z "$str" ]; then
		tmpp=0
		else
			case $devno in
					[5-8]) seltejbmode tej21;;
					[3,4,e,f]) seltejbmode tej84;;
			esac
		fi
		
	done
	
	rm -rf /etc/dahdi
	if [ -d /usr/include/dahdi ]; then
		rm -rf /usr/include/dahdi
	fi
	mkdir /usr/include/dahdi
	cd $DAHDI_SOURCE_DIR
	cp ../../include/dahdi/* /usr/include/dahdi/
	
	if [ -d /lib/modules/`uname -r`/dahdi ]; then
		rm -rf /lib/modules/`uname -r`/dahdi
	fi
	
	if [ ! -d /usr/include/zaptel ]; then
		mkdir /usr/include/zaptel
	fi
	
	cd $DAHDI_INSTALL_DIR
	echo -e "\t----------------------------------------------------------"
	echo -e "\t         Start to compile driver now......"
	echo ""
	make > /dev/null
	echo -e "\t         Start to install driver now......"
	echo ""
	make install > /dev/null
	make config > /dev/null

	if [ ! -d /usr/local/ASTBin ]; then
		mkdir /usr/local/ASTBin
	fi

	cd $DAHDI_SOURCE_DIR
  for dir_name in $driver_dir_list
  do
    cp $dir_name/*.bin /usr/local/ASTBin/
  done
  
  echo > /etc/dahdi/modules
  for dir_name in $driver_dir_list
	do
		modprobe $dir_name
		echo $dir_name >> /etc/dahdi/modules
	done		

	if [ -f $DAHDI_TOOLS_DIR/configure ];then
		cd $DAHDI_TOOLS_DIR
		echo -e "\t		Start to compile dahdi tools now ......"
		echo ""
		./configure >/dev/null
		make > /dev/null
		echo -e "\t		Start to install dahdi tools now......"
		echo ""
		make install >/dev/null
		
	fi

	echo -e "\t         Install Driver Completed"
	echo ""
	
	getyn "Would you like to configure the cards order now?" || return 0
	
	card_list_conf
}
Remove()
{
	banner
	echo "You are about to uninstall SynAST AST package!"
	getyn "\nAre you sure?" || return 0
	
	      echo " "
        echo "Removing SynAST AST modules now"
        module_list="fxm8apci fxm16apcie fxm3201p fxm3201e fxm32 tejxapci tej21 tej84 cdcx522apci"
        
        for module_name in $module_list
        do
        				rmmod $module_name
        done

        for module_name in $module_list
        do
                eval "modprobe -l |grep $module_name > /dev/null"
                if [ $? -eq 0 ]; then
                        module_path=`modprobe -l |grep $module_name`
                        \rm -f $module_path >/dev/null
                        echo "   $module_path removed"
                else
                        echo "   $module_name module not found"
                fi
        done
        echo "Probing for modules (depmod -a)..."
        eval "depmod -a"
}

Main()
{
	if [ $1 = "remove" ];then
		Remove
	elif [ $1 = "install" ];then
		Install
	else
		clear
		echo "          ./Setup {command}"
		echo "          commands:"
		echo "          -----------"
		echo "          install  	: Install SynAST"
		echo "          remove  	: Remove SynAST"
	fi
}

Main $1

