#!/bin/sh

prefix=/usr
datadir=/usr/share
pkgdatadir=${datadir}/metisse

fvwmrc_revision=5
ametistarc_revision=5

METISSE_FVWM_CONFIG_DIR=${pkgdatadir}/fvwm

print_help ()
{
    echo "Usage:

  metisse-start-fvwm [ options ] -- [FvwmAmetista options] -- [fvwm options]
         -- [Xwnc options]

metisse-start-fvwm options:

  -h        show this help and exit
  -c  path  user fvwm config dir (default ~/.fvwm-metisse)
  -Xwnc     start Xwnc (if needed) 
  -killXwnc kill Xwnc when session is closed (and if -Xwnc)
  -no-Xwnc -no-killXwnc  don't start or kill even if specified in config file
  -wd :x    display number of the Xwnc server (default :1)
  -wh host  the host of the Xwnc server (default 127.0.0.1)
  -wp pass  passowrd for Xwnc (no password by default)
  -r        re-install user configuration file 
"

}

# Arguments
fvwmArgs=""
ametistaArgs=""
whoseArgs="my"

# default
fvwmExe="fvwmi"
reInstallConfig=0
FVWMAMETISTA_DISPLAY=$DISPLAY

user_config_dir=$HOME/.fvwm-metisse

startXwnc=yes
killXwnc=if_start
XwncConfig=$user_config_dir/XwncConfig
[ -f $XwncConfig ] && . $XwncConfig

WDPY=":1"
for Xlock in /tmp/.X*-lock; do
	if [ -O $Xlock ]; then
		XPID=$(cat $Xlock)
		if ps $XPID | grep -q Xwnc; then
			XWNC_STARTED=1
			break
		fi
	fi
done
if [ -n "$XWNC_STARTED" ]; then
	WDPY="$(ps $XPID | tr " " "\n" | sed -n "/^:[0-9]*$/p")"
	echo "Xwnc already started on 127.0.0.1$WDPY (PID:"$XPID")"
fi 
WHOST="127.0.0.1"
WPASS="no"
XWNC_DISPLAY="wnc://$WHOST$WDPY"
FVWM_DISPLAY="$WHOST$WDPY"

while [ "x$1" != "x" ]; do
	case "$1" in
	--help|-help|-h)
	    print_help
	    exit
	;;
	--)
		if [ "$whoseArgs" = "my" ]; then
			whoseArgs="ametista"
		elif [ "$whoseArgs" = "ametista" ]; then
			whoseArgs="fvwm"
		elif [ "$whoseArgs" = "fvwm" ]; then
			whoseArgs="xwnc"
		fi
	;;
	*)
		if [ "$whoseArgs" = "fvwm" ]; then
			fvwmArgs="$fvwmArgs $1"
		elif [ "$whoseArgs" = "ametista" ]; then
			case "$1" in
			-d)
				shift
				FVWMAMETISTA_DISPLAY=$1
			;;
			-w)
				shift
				XWNC_DISPLAY=$1
			;;
			*)
				ametistaArgs="$ametistaArgs $1"
			;;
			esac
		elif [ "$whoseArgs" = "xwnc" ]; then
			xwncArgs="$xwncArgs $1"
		else
			case "$1" in
			--wdisplay|--wd|-wd)
				shift
				WDPY="$1"
				XWNC_DISPLAY="wnc://$WHOST$WDPY"
				FVWM_DISPLAY=$WHOST$WDPY
				if [ ! "x$WPASS" = "x" ]; then
				    XWNC_DISPLAY="$XWNC_DISPLAY?password=$WPASS"
				fi
			;;
			--whost|-wh)
				shift
				WHOST="$1"
				XWNC_DISPLAY="wnc://$WHOST$WDPY"
				FVWM_DISPLAY=$WHOST$WDPY
				if [ ! "x$WPASS" = "x" ]; then
				    XWNC_DISPLAY="$XWNC_DISPLAY?password=$WPASS"
				fi
			;;
			--wpassword|--wp|-wp)
				shift
				WPASS="$1"
				XWNC_DISPLAY="wnc://$WHOST$WDPY?password=$WPASS"
			;;
			--fvwm|-fvwm|--fvwm-exe|-fvwm-exe|-e)
				shift
				fvwmExe="$1"
			;;
			--Xwnc|-Xwnc)
				startXwnc=yes
			;;
			--killXwnc|-killXwnc)
				killXwnc=if_start
			;;
			--no-Xwnc|-no-Xwnc)
				startXwnc=no
			;;
			--no-killXwnc|-no-killXwnc)
				killXwnc=no
			;;
			-r|--r)
			    reInstallConfig=1
			;;
			-c|--c)
			    shift
			    user_config_dir="$1"
			;;
			*)
			    print_help
			    exit
			esac
		fi
	;;
	esac
	shift
done

system_fvwmrc=$METISSE_FVWM_CONFIG_DIR/config
user_fvwmrc=$user_config_dir/config

system_ametistarc=$METISSE_FVWM_CONFIG_DIR/ametistarc
user_ametistarc=$user_config_dir/ametistarc

config_files_list=$METISSE_FVWM_CONFIG_DIR/config-files-list

# sanity check 2
bad_install=0
not_found=""
if [ ! -f $system_fvwmrc ]; then
    bad_install=1
    not_found="$not_found $system_fvwmrc"
fi
if [ ! -f $config_files_list ]; then
    bad_install=1
    not_found="$not_found $config_files_list"
fi
if [ ! -f $system_ametistarc ]; then
    bad_install=1
    not_found="$not_found $system_ametistarc"
fi

if [ $bad_install = 1 ]; then
    echo "WARNING:"
    echo "WARNING: cannot found fvwm metisse config file(s):"
    echo "WARNING: $not_found"
    echo "WARNING: do you make install?"
    echo "WARNING: ABORT!"
    echo "WARNING:"
    exit 1
fi

[ -d $user_config_dir ] || mkdir -p $user_config_dir

if [ ! -d $user_config_dir ]; then
  echo "Fail to create $user_config_dir"
  echo "ABORT!"
fi

isNewVersion=0
isfvwmrcNewVersion=0
isametistarcNewVersion=0

if [ ! -f $user_fvwmrc -o $reInstallConfig = 1 ]; then
    isNewVersion=1
    isfvwmrcNewVersion=1
else
    hl="`head -1 $user_fvwmrc 2>/dev/null`"
    test "`echo $hl | cut -d' ' -f5`" = "$fvwmrc_revision"
    isfvwmrcNewVersion="$?"
fi

if [ "x$isfvwmrcNewVersion" = "x1" ]; then
    echo "[metisse-fvwm-start] Installing: $user_fvwmrc"
    cp $system_fvwmrc $user_fvwmrc
fi

if [ ! -f $user_ametistarc -o $reInstallConfig = 1 ]; then
    isametistarcNewVersion=0
elif [ ! -f $user_config_dir/fonts ]; then
    # pre 0.3.0 config
    isametistarcNewVersion=1
else
    hl="`head -1 $user_ametistarc 2>/dev/null`"
    test "`echo $hl | cut -d' ' -f5`" = "$ametistarc_revision"
    isametistarcNewVersion="$?"
fi

if [ "x$isametistarcNewVersion" = "x1" ]; then

    echo "
[metisse-fvwm-start] WARNING:
[metisse-fvwm-start] WARNING: your metisse fvwm config files do not match the
[metisse-fvwm-start] WARNING: metisse version. You may want to backup your
[metisse-fvwm-start] WARNING: $user_config_dir dir and use the
[metisse-fvwm-start] WARNING: -r option
[metisse-fvwm-start] WARNING:
"

fi

if [ ! -f $user_ametistarc -o $reInstallConfig = 1 ]; then
    if [ ! -d $user_config_dir/window ]; then
	mkdir $user_config_dir/window
    fi
    if [ ! -d $user_config_dir/colours ]; then
	mkdir $user_config_dir/colours
    fi
    for f in `cat $config_files_list`; do
	echo "[metisse-fvwm-start] Installing: $user_config_dir/$f" 
	cp -f $METISSE_FVWM_CONFIG_DIR/$f $user_config_dir/$f
    done
    rm -f $user_config_dir/.aconfig
    touch $user_config_dir/.aconfig
fi

#start Xwnc
if [ "$startXwnc" == "yes" ]; then
	XwncConfig=$user_config_dir/XwncConfig
	[ -f $XwncConfig ] && . $XwncConfig
	if [ "$WHOST" != "127.0.0.1" ]; then
		echo "WARNING: -Xwnc option passed, but Xwnc host is not localhost: $WHOST"
		echo "WARNING: Will not try to start Xwnc"
	else
		if [ ! -n "$xwncArgs" ]; then
			[ -n "$XwncOptions" ] && xwncArgs="$XwncOptions"
			[ ! -n "$xwncArgs" ] && xwncArgs="-ac"
		fi
		echo "$xwncArgs" | egrep -vq ":[0-9]" && \
			xwncArgs="$xwncArgs $WDPY"
		
		if [ -n "$XWNC_STARTED" ]; then
		  sXwncArgs=$(ps $XPID | sed -n "/Xwnc/{s/^.*Xwnc //;p}"| xargs)
		  [ "$(echo $xwncArgs | xargs )" != "$sXwncArgs" ] && cat << EOF
WARNING[Xwnc] Passed Xwnc arguments: $xwncArgs
WARNING[Xwnc] differs from started Xwnc arguments: $sXwncArgs
WARNING[Xwnc] but will not start other Xwnc
EOF
		else
		  if [ -e /tmp/.X$(echo $WDPY | cut -c 2-)-lock ]; then
		    for DPY_for_Xwnc in 1 2 3 4 5 6 7 8; do
		      if [ ! -e /tmp/.X$DPY_for_Xwnc-lock ]; then
			xwncArgs="$(echo "$xwncArgs" | \
				sed "s/$WDPY/:$DPY_for_Xwnc/")"
		        break
		      fi
		    done
		  fi
		  echo "Starting Xwnc with args $xwncArgs"
		  Xwnc $xwncArgs &
		  [ "$killXwnc" == "if_start" ] && killXwnc=yes
		fi
	fi	
fi

FVWMAMETISTA_ARGS="-d $FVWMAMETISTA_DISPLAY -w $XWNC_DISPLAY $ametistaArgs"
export FVWMAMETISTA_ARGS
export METISSE_FVWM_CONFIG_DIR

echo "Start fvwmi with args $FVWMAMETISTA_ARGS for FvwmAmetista"

env FVWM_USERDIR=$user_config_dir $fvwmExe -display $FVWM_DISPLAY $fvwmArgs

if [ "$killXwnc" == "yes" ]; then
	pid=$(cat /tmp/.X$(echo $WDPY | cut -c 2-)-lock)
	if ps $pid ; then
		kill -TERM $pid
		sleep 0.1
		ps $pid && sleep 3 && ps $pid && \
			kill -KILL $pid
	fi
fi
