#!/bin/sh

set_printcap() {
	#change the printer
	sed "s/CHANGEME/$PRINTER/" /etc/printcap.local.src | sed "s/model=hp5simopier/model=$MODEL/" > /etc/printcap.local
	cp /etc/printcap.local /etc/printcap
}

restart_services() {
	#extra stuff
	/usr/X11R6/bin/xset -dpms s 1000000
}

start_lpd() {
	#clean spool area
	/usr/bin/lprm -Pprivate all
	/usr/bin/lprm -Ppublic all
	/usr/bin/lprm -Pmediator all
	/etc/rc.d/init.d/lpd stop
	rm -rf /spare/spool
	checkpc -f
	/etc/rc.d/init.d/lpd start
}

#pre-configured stuff
JAVA_HOME="/usr/java/j2re1.4.2_08"
JAVASCRIPT_HOME="http://www.columbia.edu/acis/facilities/printers/js"
PRINTERS_HOME="http://www.columbia.edu/acis/facilities/printers/ninja"

#setup parameters
DIST="prod"
MODEL="hp4000"
PRINTER=$(hostname | sed s/-ninja/-printer/)
HOSTNAME=$(hostname)

#get params from javascript
wget -q -O /tmp/dists.html $PRINTERS_HOME/
for i in $(grep -i 'a href=' /tmp/dists.html | sed 's/<[^<>]*>//g'); do
  indistro=$($JAVA_HOME/bin/java -classpath /files/js.jar \
    org.mozilla.javascript.tools.shell.Main \
    -f $JAVASCRIPT_HOME/header.js \
    -f $PRINTERS_HOME/$i/js/printers.js \
    $JAVASCRIPT_HOME/lookup.js host $HOSTNAME host 2> /dev/null)
  if [ $? -ne 0 ];then continue;fi
  if [[ $indistro == "" ]];then continue;fi
  DIST=$i
  MOD=$($JAVA_HOME/bin/java -classpath /files/js.jar \
    org.mozilla.javascript.tools.shell.Main \
    -f $JAVASCRIPT_HOME/header.js \
    -f $JAVASCRIPT_HOME/ninja/ifhp.js \
    -f $PRINTERS_HOME/$i/js/printers.js \
    $JAVASCRIPT_HOME/lookup.js host $HOSTNAME ifhp_driver)
  if [[ $MOD != "" ]];then MODEL=$MOD;fi
  break;
done

#starup
pushd /root/.javaws/cache/http/Dwww.columbia.edu/P80/DMacis/DMfacilities/DMprinters/DMninja
if [ $DIST != prod ];then
	rm -f DM$DIST
	ln -s DMprod DM$DIST
fi
popd
set_printcap
restart_services

rm -f /var/log/prix
rm -f /var/log/rmid
rm -f /var/log/javaws
start_lpd
pushd /
$JAVA_HOME/javaws/javaws http://www.columbia.edu/acis/facilities/printers/ninja/$DIST/prix/jnlp/prix.jnlp
popd
while (true);do sleep 10000;done
