#!/bin/sh
#
# Copyright 2009 - 2016 Wachendorff Elektronik GmbH & Co. KG
#

# setup base environment
. /etc/profile

# before executing custom user scripts, make sure the environment is set up correctly:
if [ "$1" == "start" ]; then
    ### copy base fonts to user partition ###
    if [ ! -d "/opt/share/fonts" ]; then
        /bin/echo "initializing fonts: "
        /bin/mkdir -p /opt/share
        /bin/tar xzf /usr/local/Qt/lib/base-fonts.tar.gz -C /opt/share/
        /bin/sync
    fi

    if [ ! -f "/opt/share/fonts/SevenSegment.ttf" ]; then
        /bin/cp /usr/local/SevenSegment.ttf /opt/share/fonts/
        /bin/sync
    fi

    ### create /opt/var directory ###
    if [ ! -d "/opt/var" ]; then
        /bin/mkdir -p /opt/var
        /bin/sync
    fi

    ### calibrate touch screen ###
    if [ ! -s "/opt/etc/pointercal" ]; then
        /bin/echo "calibrating touch screen: "
        /bin/mkdir -p /opt/etc
        /usr/bin/ts_calibrate
        /bin/chmod 644 /opt/etc/pointercal
        /bin/sync
    fi
fi

# Now we can run the user scripts
# make sure, that user script directory exists
if [ ! -d "/opt/etc/init.d" ]; then
    /bin/mkdir -p /opt/etc/init.d
    /bin/sync
fi

# ensure proper sorting for stop and start operation
if [ "$1" == "stop" ]; then
    scripts=`/bin/ls -r /opt/etc/init.d`
else
    scripts=`/bin/ls /opt/etc/init.d`
fi

# run scripts in /opt/etc/init.d
for i in $scripts; do
    if [ -x /opt/etc/init.d/$i ]
    then                                                                        
        /opt/etc/init.d/$i $1
    fi                                                                          
done

