#!/bin/bash

. /etc/profile.d/profile.sh

#Create a session for local services
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
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=//' )
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

#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

for i in /opt/cranix-java/lib/*
do
        CLASSPATH="$i:$CLASSPATH"
done

exec /usr/lib64/jvm/jre-21-openjdk/bin/java -Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en -Duser.variant -cp $CLASSPATH de.cephalix.api.CephalixApplication server /opt/cranix-java/conf/config.yml

