##########################################################################
#   Copyright (C) 2003-2017  Weidmueller Interface GmbH & Co. KG
#   All Rights Reserved.
#
#
# Version History :
#   date        author      comment
#   12/04/2003  James       first version
#   07/01/2004  James       compatible with Real TTY V1
##########################################################################

################################################################################
# define value and default value setting
################################################################################
DirTmp=$0
DirTmp=${DirTmp%/wminst}
TempDir=$DirTmp

SECPATH="/usr/lib/secreal2"
ProductName="Weidmueller SE Converter Real TTY Driver"
ProductVer=""
OS="linux"
Device=""
check=""
EntryPwd=`pwd`

driverPath="/usr/lib/secreal2/driver"
WM_MOD=secreal2

#Parameters
WM_VERSION=3
WM_PATCH_LEVEL=0
WM_SUBLEVEL=0
WM_VERSION_CODE=$(( ($WM_VERSION<<16)+($WM_PATCH_LEVEL<<8)+$WM_SUBLEVEL ))

K_MODULE_VERSION=$(uname -r)
K_RELEASE=$(echo $K_MODULE_VERSION | sed -e "s/-.*//g")
K_VERSION=$(echo $K_RELEASE | cut -d '.' -f 1)
K_PATCH_LEVEL=$(echo $K_RELEASE | cut -d '.' -f 2)
K_SUBLEVEL=$(echo $K_RELEASE | cut -d '.' -f 3)
K_VERSION_CODE=$(( ($K_VERSION<<16)+($K_PATCH_LEVEL<<8)+$K_SUBLEVEL ))

K_SOURCE=/lib/modules/$K_MODULE_VERSION/build
LINUX_DIS=$(grep '[0-9]' /etc/issue )

################################################################################
# interrupt_quit1()
#   to quit install by interrupt or quit
################################################################################
interrupt_quit1() {
    echo "\nInstallation aborted by INTERRUPT !"
    exit 1
}
################################################################################
# interrupt_quit2()
#   to quit install by interrupt or quit
################################################################################
interrupt_quit2() {
    echo "\nInstallation aborted by INTERRUPT !"
    clean_tempfile
    exit 1
}

interrupt_nothing1() {
    exit 1
}

interrupt_nothing2() {
    clean_tempfile
    exit 1
}

################################################################################
# clean_tempfile()
################################################################################
#clean_tempfile () {
#    [ -d $TempDir ] && {
#        rm -rf $TempDir > /dev/null 2>&1
#    }
#    [ -d $SECPATH ] && {
#        rm -rf $SECPATH > /dev/null 2>&1
#    }
#    sync; sync
#}

clean_tempfile () {
     sync;
}
################################################################################
# get_OsName()
#   get the OS name.
################################################################################
get_OsName() {
    if [ -f /etc/redhat-release ]
    then
        OS="linux"
    elif [ -f /etc/SuSE-release ]
    then
        OS="SuSE"
    elif [ -f /etc/gentoo-release ]
    then
        OS="gentoo"
    elif [ -f /etc/debian_version ]
    then
        OS="debian"
    fi
}

################################################################################
# check_env()
#   Check the environment for installation
################################################################################
check_env() {
#Check kernel source
if test  ! -e $K_SOURCE
then
echo "*********************************ERROR****************************************************"
echo " Unable to locate matching source for kernel $K_MODULE_VERSION."
echo " Please install proper kernel-header/source or contact support.automation@weidmueller.com."
echo "******************************************************************************************"
exit 1
fi

#Check supported kernel version
if test $K_VERSION_CODE -gt $WM_VERSION_CODE
then
echo "********************************WARNING*****************************************************"
echo " $ProductName may not be compatible with"
echo " Linux Kernel versions $K_MODULE_VERSION ."
echo " To download the available driver, please visit visit Weidmueller at: http://weidmueller.com"
echo " If you have questions, please contact Weidmueller support at: support.automation@weidmueller.com"
echo "********************************************************************************************"
exit 1
fi
}

################################################################################
# chk_libssl()
#   Check /usr/lib/libssl.so.x
#   and link to /tmp/weidmueller/libsll.so 
################################################################################
chk_libssl() {
	sslpath=$(find /usr/lib64 -name "libssl.so*" 2> /dev/null)
	
    if [ -z "$sslpath" ]
	then
		sslpath=$(find /usr/lib -name "libssl.so*" 2> /dev/null) 
		newsslpath=$(find /usr/lib/i386-linux-gnu -name "libssl.so*" 2> /dev/null) 
        if [ -z "$sslpath" ]
        then
        	echo
        	echo 'Can not find libssl.so file in your system,'
        	echo 'Please install openssl package if you want to use'
        	echo 'security function.'
        	exit 0
       	else
		if [ -z "$newsslpath" ]
		then
			echo "libssl.so.x.x in /usr/lib/"
       			ls /usr/lib | grep libssl.so* | head -1 |
	       		awk '{system("ln -s /usr/lib/"$0 " libssl.so")}'
		else
			echo "libssl.so.x.x in /usr/lib/i386-linux-gnu"
       			ls /usr/lib/i386-linux-gnu | grep libssl.so* | head -1 |
	       		awk '{system("ln -s /usr/lib/i386-linux-gnu/"$0 " libssl.so")}'
		fi
       	fi
    else 
       	ls /usr/lib64 | grep libssl.so* | head -1 |
       	awk '{system("ln -s /usr/lib64/"$0 " libssl.so")}' 
    fi 
}

########################################################
#
# Main procedures
# To read the shell program input argument and process it.
#
########################################################
trap interrupt_quit1 1 3 9 15           # trap signal
trap interrupt_nothing1 2

if [ "$#" -ge 3 ]
then
    print_usage
    exit 1
fi

ProductVer=`awk '{if($2=="SECREAL_VERSION"){print $3}}' sec_ver.h`

echo -n "
===============================================================================
Copyright (C) 2002-2015  Weidmueller Interface GmbH & Co. KG
All Rights Reserved.

$ProductName "

echo -n $ProductVer | sed s/\"//g

echo " Installation.
System Information: Kernel `uname -r`; Machine `uname -m`.
===============================================================================
"

check_env 

get_OsName

if [ "$OS" = "debian" ] 
then
    touch /etc/init.d/secreals
fi

trap interrupt_quit2 1 3 9 15       # trap signal
trap interrupt_nothing2 2           # trap signal SIGINT


########################################################
# check configuration file. (secreal2d.cf)
########################################################
if [ -f /usr/lib/secreal2/driver/secreal2d.cf ]
then
    echo 'There is an Real TTY Driver installed in your system.'
    echo 'Continue to install will overwrite the old driver.'
    echo 'Do you want to continue installing? [y/N].'

    read check
    case $check in
    [n])
        exit 0
        ;;
    [N])
        exit 0
        ;;
    [y])
        ;;
    [Y])
        ;;
    *)
        exit 0
        ;;
    esac
fi

########################################################
# rmmove module
########################################################
ps -ef | grep secreal2d | awk '$0 !~ /grep/ {system("kill -15 "$2)}'
ps -ef | grep secreal2d | awk '$0 !~ /grep/ {system("kill -9 "$2)}'
lsmod | grep secreal2 |
awk '$0 != "" {system("rmmod secreal2")}'


########################################################
# install driver
########################################################
echo ''

echo "Building driver..."


mkdir -p /lib/modules/`uname -r`/kernel/drivers/char > /dev/null 2>&1
mkdir -p /lib/modules/`uname -r`/misc > /dev/null 2>&1

echo
echo 'If you want to use secure communication with target,'
echo 'you might choose [y] to enable the SSL function.'
echo 'Note: This function support RealCOM with secure mode only.'
echo 'Do you want to enable secure function? [y/N].'

read check
case $check in
[n])
    if [ "$1" = "SP1" ]
    then
        make $1 PATH1=$(pwd)
	elif [ "$1" = "polling" ]
	then
		make clean
		make all PATH1=$(pwd) POLLING=-DOFFLINE_POLLING
    else
        make all PATH1=$(pwd)
    fi 
    ;;
[N])
    if [ "$1" = "SP1" ]
    then
        make $1 PATH1=$(pwd)
	elif [ "$1" = "polling" ]
	then
		make clean
		make all PATH1=$(pwd) POLLING=-DOFFLINE_POLLING
    else
        make all PATH1=$(pwd)
    fi 
    ;;
[y])
	if [ ! -f "$TempDir/libssl.so" ]
	then
		chk_libssl
	fi

	if [ "$1" = "SP1" ]
	then
		make SP1_ssl PATH1=$(pwd)
	elif [ "$1" = "m64" ]
	then
		make ssl64 PATH1=$(pwd)
	elif [ "$1" = "mppc64" ]
	then
		make ppc64 PATH1=$(pwd)
	elif [ "$1" = "SP1_m64" ]
	then
		make SP1_ssl64 PATH1=$(pwd)
	elif [ "$1" = "polling" ]
	then
		make clean
		make ssl PATH1=$(pwd) POLLING=-DOFFLINE_POLLING
	else
		make ssl PATH1=$(pwd)
	fi 
    ;;
[Y])
	if [ ! -f "$TempDir/libssl.so" ]
	then
		chk_libssl
	fi

	if [ "$1" = "SP1" ]
	then
		make SP1_ssl PATH1=$(pwd)
	elif [ "$1" = "m64" ]
	then
		make ssl64 PATH1=$(pwd)
	elif [ "$1" = "mppc64" ]
	then
		make ppc64 PATH1=$(pwd)
	elif [ "$1" = "SP1_m64" ]
	then
		make SP1_ssl64 PATH1=$(pwd)
	elif [ "$1" = "polling" ]
	then
		make clean
		make ssl PATH1=$(pwd) POLLING=-DOFFLINE_POLLING
	else
		make ssl PATH1=$(pwd)
	fi 
    ;;
*)
	if [ "$1" = "polling" ]
	then
		make clean
		make all PATH1=$(pwd) POLLING=-DOFFLINE_POLLING
	else
		make $1 PATH1=$(pwd)
	fi
    ;;
esac

echo "Check Driver..."
[ -e $WM_MOD.o -a -e secreal2d.o -a -e secreal2d_redund ] || {
    echo "FAILED !!!"
    echo " "
    echo "Install Not Completed !"
    echo " "
    clean_tempfile
    exit 0
}


########################################################
# Process File
########################################################
#$TempDir/npfile

flag=0

mkdir -p $SECPATH > /dev/null 2>&1
mkdir -p $driverPath > /dev/null 2>&1


[ -f /usr/lib/secreal2/driver/secreal2d.cf ] || {
    echo -n "Copying configurations files ... "
    cp -f $(pwd)/secreal2d.cf $driverPath

    flag=$?
    [ $flag = 0 ] ||    {
        echo "FAILED! ($flag)"
        exit 0
    }
    echo "OK!"
}


### driver ###
NowPath=$(pwd)
echo -n "Copying driver files ... "
cp -f $NowPath/killp       $driverPath
cp -f $NowPath/secreal2d_redund    $driverPath
cp -f $NowPath/secreal2d    $driverPath
#cp -f $NowPath/$WM_MOD   $driverPath
cp -f $NowPath/Makefile    $driverPath
cp -f $NowPath/secreal2d.c  $driverPath
cp -f $NowPath/secreal2.h  $driverPath
cp -f $NowPath/secreal2d.cf $driverPath/config
cp -f $NowPath/secreal2.c   $driverPath
#cp -f $NowPath/linux.mak   $driverPath
cp -f $NowPath/wmaddsvr    $driverPath
cp -f $NowPath/wmdelsvr    $driverPath
cp -f $NowPath/wmcfmat     $driverPath
cp -f $NowPath/wmloadsvr   $driverPath
cp -f $NowPath/wmmknod     $driverPath
cp -f $NowPath/wmrmnod     $driverPath
cp -f $NowPath/wmuninst    $driverPath
cp -f $NowPath/wmsetsec    $driverPath
cp -f $NowPath/README.TXT  $SECPATH
cp -f $NowPath/VERSION.TXT $SECPATH
cp -f $NowPath/kernel2.6.txt $SECPATH
echo "OK!"



### module ###
#cp -f $driverPath/secreal2.o /lib/modules/`uname -r`/kernel/drivers/char
#cp -f $driverPath/secreal2.o /lib/modules/`uname -r`/misc


ps -ef | grep secreal2 |
awk '$0 !~ /grep/ {system("kill -15 "$2)}'
ps -ef | grep secreal2 |
awk '$0 !~ /grep/ {system("kill -9 "$2)}'





########################################################
# load module
########################################################
echo "Load driver..."
modprobe $WM_MOD 
[ "$?" = "0" ] || {
    echo ""
    echo "Failed!!!  please contact the provider"
    echo ""
    exit 0
}
echo "OK!"


########################################################
# Delete the line with secreal2 and append
# "modprobe secreal2" in /etc/rc.d/rc.local.
########################################################


cd $SECPATH/driver
./wmloadsvr install
echo ''

echo "
===============================================================================
Installation process is completed.
The all driver files are installed on /usr/lib/secreal2/driver.
Now you can "cd /usr/lib/secreal2/driver" and run "./wmaddsvr" to add tty port.
===============================================================================
"

#[ -d $TempDir ] && {
#    rm -rf $TempDir > /dev/null 2>&1
#}

