#!/bin/bash
#
#
#	***	***	     /usr/bin/hf  		***	***
#	***					 		***
#	***	    	 Main Start Script for 	 		***
#	***	          /usr/bin/hfkernel	     		***
#	***	         and /usr/bin/hfterm			***
#	***	        by Guenther Montag DL4MGE		***
#	***					 		***
#	***	***	***	***	***	***	***	***	
#
#
#
# There is a system-wide config file: /etc/hf.conf
# I will prepare the same defaults here and there, 
# they will work in most cases.
# This script will include the config file,
# so that the settings there will overwrite those here.
# (Especially for KNOPPIX linux users, it is good to have /etc/hf.conf
# because if the system runs from cd, you have no write access to this 
# file which should have root access only be in /usr/bin.)

## There is a lot of documentation in English and German!
## See comments in /etc/hf.conf, 
## See the HF-HOWTO in the doc subdirectory of hf package,
## See F1 in the hfterm window!
## To configure /etc/hf.conf just remove the single comment signs 
## in the lines you need.

# Thanks for all help to all friends from the mailing list,
# to the authors of 'man bash', 'man dialog', 'man test'
# and to Jan Ondrej, Takashi Iwai, Bernd Kaindl 
# for their good ideas which I borrowed from 'alsaconf' !

## PREPARATIONS ......... #####################################################

## see who has started me #####################################################
startuser=`whoami`

## prepare "TELL" as a dialog-like function or just echo, #####################
## depends on X or console ####################################################
if which dialog > /dev/null; then
  DIALOG=dialog
else
  if which whiptail > /dev/null; then
    function whiptail_wrapper() {
      X1="$1"
      X2="$2"
      if [ $1 = --yesno ]; then
        X3=`expr $3 + 2`
      else
        X3=$3
      fi
      shift 3
      whiptail "$X1" "$X2" $X3 "$@"
    }
    DIALOG=whiptail_wrapper
  else
    echo "Sorry, dialog or whiptail not found."
    DIALOG=
    fi
fi

function tell {
if  [ !  $DISPLAY  ] ; then
    if [ ! -z "$DIALOG" ]; then
        dialog \
        --title "hf startscript" \
        --backtitle "HF  -  CW-ELBUG AMTOR GTOR PACTOR RTTY MT63 ham radio program"  \
        --msgbox \
"***********************************************************
$1
" 20 63 || exit 0
    fi
else
    echo "$1"
fi
};

## Prepare silent execution of functions i am lazy ############################ 
## taken from /etc/rc.config, there are still some more like this ...
rc_done="\033[71G\033[32mdone\033[m"
rc_failed="\033[71G\033[31m\033[1mfailed\033[m"

## Prepare greeting message: ##################################################
function greeting {
tell "
Hello, $startuser, I am $0,
the main start script for hfkernel and hfterm,
a ham radio CW-RTTY-AMTOR-GTOR-PACTOR-MT63
program system with TCP and F6FBB interface.
My main configuration file is /etc/hf.conf.
Short help is: man hfkernel, man hfterm, man hf.
More  help in: /usr/share/<doc>/<packages/>hf/HF-HOWTO
or in the graphic 'hfterm' by F1.
The homepage of hf is http://hfterm.sf.net.
You are welcome to subscribe our mailing list:
http://lists.sf.net/lists/listinfo/hfterm-hackers 
(then mail to hfterm-hackers@lists.sf.net )
Have a lot of fun!
"
};

## Preset Defaults: ###########################################################
serial=
audio=/dev/dsp
alsa_prefix=
x_prefix=
timecorr=1  
soundcorr=1
kerneloptions=
config_file=/etc/hf.conf
proc_mhzcorr=`cat /proc/cpuinfo | grep MHz | cut -c 11- | head -n 1`
# the head is for the case you have 2 processors, like me, .... ..  !!!

## if not yet there, make a directory for the program's files ################
## and fill it with examples, e.g. text macos for cq asnd so on ##############
function makepersonaldir {
cd $HOME
    if [ ! -d hf ] ; then 
    	tell "
	
There is still no hf directory 
in your home directory.
I will try to make it ...
	
	"
	mkdir hf
        if [ ! -d hf ] ; then 
            tell "

Sorry,	    
could not make hf dir in your home dir
	    
	    "
	elif [ -d hf ] ; then
            tell "
	    
o.k., 	    
and now I will fill your hf dir 
with examples, e.g. text macros...
	    
	    "
	    cp -ruv /usr/share/hf/hf-examplefiles/* ./hf 
	    if [ $? -eq 0 ]; then
	    tell "

Examplefiles prepared.

	    "
	    else
	    tell "
	    
could not copy examplefiles.
Please check if 
/usr/share/hf/hf-examplefiles/... is there.

	    "
	    fi
        fi
    fi
};

## Start hfkernel function: ###################################################
function startkernel {
tell "
I will run now:
$background_display 
$alsa_prefix 
/usr/bin/hfkernel 
    -a $audio
    -p $serial 
    -m $mhz -t $timecorr -s $soundcorr 
    $kerneloptions
If you see the rolling numbers:
corrout: ... intermediate:  ..., o.k.!
For any errors, see /usr/share/hf/HF-HOWTO !
You can stop the hfkernel with <Strg> c.
"
$background_display $alsa_prefix /usr/bin/hfkernel \
-a $audio -p $serial \
-m $mhz -t $timecorr -s $soundcorr \
$kerneloptions 
};

## START OF REAL WORK #########################################################

## see if run under xterm or 'black' console: #################################
if test $DISPLAY ; then 
    echo x is running.
    background_display=$x_prefix
fi

## greeting ###################################################################
greeting

## Hint and exit if options given by mistake: #################################
if [ ! -z $1 ] 
then
    tell "

Sorry, the hf script is not prepared to accept options.

To configure the package, 
please just edit /etc/hf.conf.


"
exit 0
fi

## include and evaluate config file: ##########################################
if [ -r $config_file ]; then
    . $config_file 

tell "
/proc/cpuinfo thinks your cpu runs with $proc_mhzcorr Mhz.

OPTIONS from main configuration file	$config_file: 
Serial ptt:                     $serial 
Audio:                          $audio
ALSA_prefix:                    $alsa_prefix
Graphic hfkernel display:       $x_prefix
Other options to hfkernel:      $kerneloptions 
Corrected cpu frequency:        $mhzcorr
Time correction:                $timecorr 
Soundcard clock correction:     $soundcorr
"
else
    tell "

Sorry, 
could not find 
configuration file $config_file.
Let's hope the defaults in $0 
will work...

"
fi
if [ ! -z $mhzcorr ]; then
    mhz="$mhzcorr"
else 
    mhz="$proc_mhzcorr"
fi

## Check and hint, if serial is already used ##################################
if [ ! -z $serial ] ; then
    shortserial=`echo $serial | cut -c 6- `
#    tell "$shortserial"
    serialprocess=`ps -ax | grep $shortserial | grep -v grep ` 
#    tell "$serialprocess"
    if [ ! -z "$serialprocess" ]; then
	tell "
Sorry,
The serial line $serial is already in use by 
$serialprocess 

Maybe you can stop that process,
or you will have to select another serial port
in /etc/hf.conf.
"
    exit 1
    fi
fi

## setting the suid-bit to hfkernel if not yet set
teststring=`ls -l \`which hfkernel\` | grep "rwsr-xr-x" `
if [ ! -z "$teststring" ]; then
    tell "
hfkernel must run with root rights.
The suid bit has already been set
for hfkernel at the installation.
Be aware that this can be a security hole.
"
    else 
        if [ `id -u` -eq 0 ]; then
	# if root
            tell "
hfkernel must run with root rights.
The suid bit has to be set 
so that non-root users can run it.
But be aware that this can be a security hole.
I will do this now by :
\"chmod 4755 /usr/bin/hfkernel\".

"
	    chmod 4755 /usr/bin/hfkernel &> /dev/null
	else
# if not root
	    tell "
hfkernel must run with root rights.
The suid bit has to be set 
so that normal users can run it.
Be aware that this can be a security hole.
Please do as root
\"chmod 4755 /usr/bin/hfkernel\".
or start this script again as root.
"
	    exit 1
	fi
fi

## if root, start the hfkernel only: ##########################################
if  [ `id -u` -eq 0 ] ; then
    tell "
For you, root, I will start only hfkernel 
for test purposes.

If it works o.k., and you want to run 
the whole program (including graphic terminal),
become normal user, start X, 
and start the whole program with /usr/bin/hf.

"
    startkernel 
    echo -e "hfkernel has been terminated" $rc_done
    exit 0
fi

## if not root, but text console, ############################################
## make personal dir and then start the hfkernel only: #######################
if  [ ! $DISPLAY ]; then 
    makepersonaldir
    tell "
You started me from a console.
So I will start hfkernel for test only.

If it works o.k., and you want to run 
the whole program (including graphic terminal),
start X, 
and start the whole program with /usr/bin/hf.

"
    startkernel 
    echo -e "hfkernel has been terminated." $rc_done
    exit 0
fi

## if not root, and if not on text console, try to start everything:  ########
if  [ $DISPLAY ] ; then 
    makepersonaldir
    background_display=$x_prefix    
# start the hfkernel on xterm in the background ###############################
    startkernel &
    sleep 1
# see if hfterm is running    
    hfterm=`pidof hfterm`
    if [ $hfterm ] ; then
	tell "hfterm is running already under X. I restart it."
	kill $hfterm
    fi
    tell "
You called me under X, and not as root.
So why not start hfterm?
Sorry, I still have some problems with UTF-8...
I will remember your LANGUAGE
and set LANG to de_DE.ISO-8859-1 for a while...
Then I will start /usr/bin/hfterm.
"
OLDLANG=$LANG
LANG=de_DE.ISO-8859-1    
/usr/bin/hfterm
fi

## Cleanup ####################################################################
# kill hfkernel, if still running after hfterm is finished
# (if hfterm is finished the normal way, it kills hfkernel by itself)

LANG=$OLDLANG
echo "reset LANG to $LANG"

hfkernel=`pidof hfkernel`
if [ $hfkernel ] ; then
    echo -e "hf: sending the kill signal to hfkernel ... " 
    hfkernel -k
    sleep 1
    echo -e "hfkernel has been terminated." $rc_done
    exit 0
fi
echo -e "hfkernel seems to have been terminated." $rc_done
exit 0
