#!/bin/sh
# Default functions definition

# Wait until file appears then run it
WaitFile() { # [-seconds_to_wait] file
  case "$1" in
    -*) SLEEP=${1##-}; shift;;
    *) SLEEP=10;
  esac
  N=0
  while [ "$N" != "$SLEEP" ]
  do
    if [ -f "$1" ]; then return 0; fi
    N=$(($N + 1))
    sleep 1
  done
  return 1
}

# If program exists in path
Which() { # Program
  which "$1" >/dev/null 2>&1
}

# run program if exists
Run() { # Program [parameters]
  Which "$1" && { "$@" & }
}

# Start program an wait it for display
XToolWait () { # program [parameters ...]
  if Which xtoolwait
  then
    Which "$1" && xtoolwait "$@"
  else
    Which "$1" && "$@" & sleep ${NoXtoolwait:-1}
  fi
}

# Get root window width and height
GetWH() {
  local A
  if Which xwininfo
  then
    A=`xwininfo -root | tr '\n' ' '`
    Height=${A##* Height: }; Height=${Height%% *}
    Width=${A##* Width: }; Width=${Width%% *}
  else
    Height=1280
    Width=1024
  fi
}

# Programs to start before window wanager
Before_W_M() {
  GetWH
}

# Window wanager
W_M() {
  ctwm -W 1>&2 &
}

# Wall clock
Clock() {
  XToolWait tclock -geometry +0+0 -scale ${TclockScale:-0.5} -bg NavajoWhite2 -border '#413d00'
}

# Remap mouse buttons if needed
ReButton() {
  BUTTONS=`xmodmap -pp | head -1 | sed 's/.* \([0-9][0-9]*\).*/\1/'`
  test 5 -lt $BUTTONS -a 8 -gt $BUTTONS && xmodmap -e "pointer = 1 2 3 6 7 4 5"
}

# Set approporiate root window properties: cursors etc.
SetRoot() {
  xsetroot -rv -cursor ~/bitmaps/arrow ~/bitmaps/arrow_mask
}

# Set XServer properties: bell, dpms etc.
SetProps() {
  xset b 10 8820 60 s 600 c 1 +dpms
}

# Call screensaver/autolocker
ScreenSaver() {
  Which xlock && Run xautolock -time 5 -corners '-++-' -cornerdelay 2 -locker "`which xlock` -erasemode no_fade -lockdelay 60 -mode random" ||
  Run xscreensaver -no-splash
}

# now load local redefinitions
test -r $HOME/.xinitrc.local && . $HOME/.xinitrc.local

Before_W_M
W_M && wmpid="$!"
ReButton
Clock
SetRoot
SetProps
ScreenSaver
# we expect ctwm have already prepared $HOME/tmp/callxterm
WaitFile $HOME/tmp/callxterm && sh $HOME/tmp/callxterm&

wait "$wmpid"
