#!/bin/bash

. /etc/sysconfig/cranix
. /etc/profile.d/profile.sh

#Create a session for local services
TOKEN=$( grep de.cranix.api.auth.localhost= /opt/cranix-java/conf/cranix-api.properties | sed 's/de.cranix.api.auth.localhost=//' )
SQLUSER=$( grep javax.persistence.jdbc.user= /opt/cranix-java/conf/cranix-api.properties | sed 's/javax.persistence.jdbc.user=//' )
SQLPW=$( grep javax.persistence.jdbc.password= /opt/cranix-java/conf/cranix-api.properties | sed 's/javax.persistence.jdbc.password=//' )
LOCAL_TOKEN=$( echo "SELECT COUNT(*) FROM Sessions WHERE token='$TOKEN'" | mysql CRX -u $SQLUSER -p${SQLPW} | tail -n 1 )
if [  "${LOCAL_TOKEN}" = 0 -o "${CRANIX_RESET_REGISTER_PASSWORD}" = "yes" ]; then
	grep -q de.cranix.api.auth.localhost= /opt/cranix-java/conf/cranix-api.properties || echo de.cranix.api.auth.localhost=TOKEN >> /opt/cranix-java/conf/cranix-api.properties
	TOKEN="localhost_"$(uuidgen)
	sed -i s/de.cranix.api.auth.localhost=.*/de.cranix.api.auth.localhost=$TOKEN/ /opt/cranix-java/conf/cranix-api.properties
	chmod 600 /opt/cranix-java/conf/cranix-api.properties
	echo "DELETE FROM Sessions WHERE IP='127.0.0.1'" | mysql -u $SQLUSER -p${SQLPW} CRX
	echo "INSERT INTO Sessions SET user_id=1,ip='127.0.0.1',token='$TOKEN'" | mysql -u $SQLUSER -p${SQLPW} CRX
fi
#Create recreate the printer driver files if neccesarry
if [ -e /usr/share/cranix/templates/printers.txt -a -e /usr/share/cranix/templates/drivers.txt ]; then
        NEWER=$( find /usr/share/cups -name '*ppd.gz' -newer /usr/share/cranix/templates/printers.txt )
        if [ "$NEWER" ]; then
                /usr/share/cranix/tools/CreatePrinterPpd.pl
        fi
else
        /usr/share/cranix/tools/CreatePrinterPpd.pl
fi

#Register the server if not already done
if [ ! -e /etc/zypp/repos.d/CRANIX.repo -o ! -e /srv/salt/repos.d/salt-packages.repo ]; then
        /usr/share/cranix/tools/register.sh
fi

#Create lock dir if not exists
if [ -d /run/lock/cranix-api ]; then
        mkdir -p /run/lock/cranix-api
fi

CLASSPATH=""
for i in /opt/cranix-java/lib/*
do
        CLASSPATH="$i:$CLASSPATH"
done
exec java -Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en -Duser.variant -cp $CLASSPATH de.cranix.api.CranixApplication server /opt/cranix-java/conf/config.yml

