#!/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.
# After this I will include the config file,
# so that the defaults can be overwritten.
# (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 here.)

## There is a lot of documentation in English and German!
## See comments in /etc/hf.conf, 
## See README or LIESMICH in doc subdirectory of hf package,
## See F1 in the hfterm window!
## To configure, 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  -  Tom Sailer's AMTOR GTOR PACTOR RTTY ham radio program"  \
        --msgbox \
"***********************************************************
$1
" 20 63 || exit 0
    fi
else
    echo "$1"
fi
};

## Prepare silent execution of functions i am lazy ############################
silent=" > /dev/null 2>&1 "
## and a gag...
rc_done="\033[71G\033[32mdone\033[m"

## Prepare greeting message: ##################################################
function greeting {
tell "
Hello, $startuser, I am $0,
the main start script for hfkernel and hfterm,
Tom Sailer's ham radio RTTY-AMTOR-GTOR-PACTOR-MT63 package
with F6FBB mailbox interface.
If you have to configure the package, edit /etc/hf.conf.
Short help is: man hf, man hfkernel, man hfterm.
Long help is: /usr/share/doc/<packages/>hf/HF-HOWTO
and in 'hfterm' under X: 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 
and mail to hfterm-hackers@lists.sf.net 

May the source be with you.
"
};

## Preset Defaults: ###########################################################
serial=
audio=/dev/dsp
sound_starter=
alsa_prefix=
x_prefix=
socket=/var/run/hfapp
root_trick=suid
timecorr=1  
soundcorr=1
kerneloptions=
config_file=/etc/hf.conf
proc_mhzcorr=`cat /proc/cpuinfo | grep MHz | cut -c 11-`
mailbox_host=127.0.0.1
mailbox_port=6300

## 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 try to 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.
See if /usr/share/hf/hf-examplefiles/...
is there.

	    "
	    fi
        fi
    fi
};

## Start hfkernel function: ###################################################
function startkernel {
tell "
I will run now:
$x_prefix $alsa_prefix $root_prefix 
/usr/bin/hfkernel 
-a $audio
-c $socket -p $serial 
-m $mhz -t $timecorr -s $soundcorr 
$kerneloptions
If you see the rolling numbers:
corrout: ... intermediate:  ..., o.k.!
If error with 'MMAP': try option ' -n ' !
For any other errors, see the HF-HOWTO !
You can stop the hfkernel with <Strg> c.
"

$x_prefix $alsa_prefix $root_prefix /usr/bin/hfkernel \
-a $audio -c $socket -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.
    x_prefix="xterm -e"
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 $config_file: 
serial ptt: $serial
audio: $audio
sound_starter: $sound_starter alsa_prefix: $alsa_prefix
socket hfkernel<-->hfterm: $socket
workaround for non-root to start hfkernel: $root_trick
hfterm is instructed to connect F6FBB mailbox
at host $mailbox_host, port $mailbox_port.
other options to hfkernel: $kerneloptions 
correction of cpu frequency: $mhzcorr
time correction factor: $timecorr 
soundcard clock correction factor: $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
if [ $root_trick = "su1"  -o  $root_trick = "sudo" ]; then
    root_prefix=$root_trick
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

## if suid wished as root-workaround (default!), set it in fact ###############
## by setting the suid-bit to hfkernel
if [ $root_trick = "suid" ]; then
    teststring=""
    ls -l `which hfkernel` | grep "rwsr-xr-x" \
    && teststring="suid-bit is set"
    #tell "$teststring"
    if [ ! -z "$teststring" ]; then
    tell "
hfkernel must run with root rights.
As default, 
\"suid\" has been configured as workaround
so that normal users can run it.
But be aware that this can be a security hole.
The suid bit has already been set
for hfkernel.
"
    else 
        if [ `id -u` -eq 0 ]; then
	# if root
            tell "
hfkernel must run with root rights.

As default, 
\"suid\" has been configured as workaround,
so that non-root users can run it.
But be aware that this can be a security hole.

I will do now:
\"chmod 4755 /usr/bin/hfkernel\".

"
            chmod 4755 /usr/bin/hfkernel $silent
        else
	# if not root
	    tell "
hfkernel must run with root rights.
As default, 
\"suid\" has been configured as workaround
in /etc/hf.conf 
so that normal users can run it.
But 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
fi

## start oss driver, if needed: ###############################################
$sound_starter

## 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 
    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 
    exit 0
fi

## if not root, and if not on text console, try to start everything:  ########
# prepare hfterm: 
if  [ $DISPLAY ] ; then 
    makepersonaldir
    tell "
    You called me under X, and not as root.
    So I will start hfkernel in an xterm in the background,
    and then I will start hfterm.
    "
    x_prefix="xterm -e"
    
# start the hfkernel on xterm in the background ###############################
#echo "Now I will hand over to /usr/bin/hfkernel."
    startkernel &
    sleep 1
# start hfterm, connected with the unix domain socket hfapp
# and, if you want, with the options for the mailbox host and port.
    /usr/bin/hfterm -k /var/run/hfapp -h $mailbox_host -p $mailbox_port
fi

## Cleanup ####################################################################
# kill hfkernel silently after hfterm is finished
#echo "hf: sending hfkernel the kill signal ..."
$root_prefix /usr/bin/hfkernel -k 
exit 0