#!/bin/sh
#
# Desktop session init script.
# Author: T.Jokiel <http://porteus-kiosk.org>

# Setup variables:
. /etc/profile.d/variables.sh
PTH=/usr/share/icons/oxygen/22x22
[ -x /opt/google/chrome/chrome ] && chrome=yes
wget="wget --no-http-keep-alive --no-cache --no-check-certificate"

# Check if correct kernel version is used:
[ `lsmod | wc -l` -lt 3 ] && { dunstify -u critical -i /usr/share/icons/oxygen/48x48/status/dialog-warning.png "Kernel version: `uname -r` does not match the modules version: `ls /lib/modules/ | tr '\n' ' '`\nPerhaps the system was booted from usb stick while older kiosk installation exist on the hard drive.\nTo force booting from removable device please install the system with following parameter added to kiosk config: 'kernel_parameters=boot_from_usb'."; sleep 60; init 0; }

# Load snd-usb-audio so USB audio devices are always on the last sound card slot:
modprobe snd-usb-audio

# Start battery polling:
battery=`ls -1 /sys/class/power_supply/*/capacity 2>/dev/null | head -n1 | cut -d/ -f5`
[ "$battery" ] && sh /opt/scripts/battery_polling $battery &

# Disable input devices or configure them:
#disable_input=yes
if [ "$disable_input" ]; then
    xinput | egrep -v 'Virtual core| Button' | cut -d= -f2 | cut -d[ -f1 | while read line; do xinput --disable $line 2>/dev/null; done
else
    # Set keyboard mapping:
    setxkbmap -layout us,lay2 -variant ,var2 2>/dev/null

    # Enable numlock:
    xdotool key Num_Lock

    # Autohide mouse pointer after X seconds of inactivity:
    (
    sleep 5; #hhpc -i 5 &
    ) &

    # Disable right mouse click:
    xmodmap -e "pointer = 1 2 32 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 3"

    # Disable middle and right mouse clicks:
    #xmodmap -e "pointer = 1 31 32 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 2 3"

    # Set custom mouse speed:
    #xset m 20/10

    # Calibrate touchscreen:
    #. /opt/scripts/calibrate.sh

    # Force touch gestures for Chrome:
    #[ "$chrome" ] && id=`xinput_calibrator --list | cut -s -d= -f2-`; [ "$id" ] && { for x in $id; do tdev="$x,$tdev"; done; tdev=`echo $tdev | sed 's/,$//'`; grep -q touch-devices $chflags || echo -e "--touch-devices=$tdev\n--enable-pinch" >> $chflags; }
fi

# Screen setup:
#parse=yes
if [ "$parse" ]; then
    /opt/scripts/screen-setup-parse "$parse"
else
    # Rotate screen:
    #for display in `xrandr | grep -w connected | cut -d" " -f1`; do xrandr --output $display --rotate normal; done

    # Rotate touch input:
    #rtouch=yes
    [ "$rtouch" ] && ( sleep 4; /opt/scripts/rotate-touch $rtouch; ) &

    # Set custom screen resolution/refresh rate:
    #/opt/scripts/set-resolution-rate cres crate

    # Set brightness:
    for x in `ls -1 /sys/class/backlight`; do echo $((`cat /sys/class/backlight/$x/max_brightness`*100/100)) > /sys/class/backlight/$x/brightness; done

    # Scale screens:
    /opt/scripts/scale-screen
fi

# Set wallpaper according to current screen size:
hsetroot -fill /usr/share/wallpapers/default.jpg

# Enable real transparency:
#xcompmgr &

# Disable DPMS Xorg features and builtin screen-saver:
xset -dpms; xset s 0

# Freeze/standby/suspend/shutdown system in case when no activity is detected:
#FREEZEIDLE=300
#STANDBYIDLE=300
#SUSPENDIDLE=300
#SHUTDOWNIDLE=300
if [ "$FREEZEIDLE" ]; then /opt/scripts/freeze-idle-watcher &
elif [ "$STANDBYIDLE" ]; then /opt/scripts/standby-idle-watcher &
elif [ "$SUSPENDIDLE" ]; then /opt/scripts/suspend-idle-watcher &
elif [ "$SHUTDOWNIDLE" ]; then /opt/scripts/shutdown-idle-watcher &
fi

# Restrict access for guest to sensitive directories/files:
chmod 700 /etc/rc.d /etc/X11 /etc/xdg /lib/modules /opt/scripts /root 2>/dev/null
chmod 600 /etc/inittab /etc/shadow /etc/wpa_supplicant.conf /etc/ssh/sshd_config 2>/dev/null
chmod 640 /var/log/Xorg.0.log*

# Set sound level:
/etc/rc.d/rc.sound &

# We are in the GUI - this is good, lets keep the PC running infinitely. Network issues can be resolved by 'run_command=':
[ -e /dev/watchdog ] && /usr/sbin/wd_keepalive

# Launch first-run wizard:
[ -e /opt/scripts/first-run ] && su -c /opt/scripts/first-run

# Wait on network connection before proceeding (skip gateway check for dialup connections):
GTW=`route -n | grep -c " UG "`; [ `route -n | grep -c -w ppp0` = 1 ] && GTW=1
if [ $GTW -lt 1 ]; then
    SLEEP=120
    while [ $GTW -lt 1 -a $SLEEP -gt 0 ]; do [ $SLEEP = 60 ] && sh /etc/rc.d/rc.inet1; sleep 1; let SLEEP=SLEEP-1; GTW=`route -n | grep -c " UG "`; done
fi
[ "$GTW" -lt 1 ] && dunstify -u normal -i $PTH/status/dialog-warning.png "Gateway is not set - network may be not available."

# Pull time from NTP server and set hardware clock to system time:
( while true; do ntpdate pool.ntp.org && hwclock --utc -w; sleep 24h; done; ) &

# Setup proxy auto configuration:
#proxypac=
if [ "$proxypac" ]; then
    pkget $proxypac /opt/scripts/proxy.pac
    # Default to first IP in case multiple proxies are returned:
    proxy=`pactester -p /opt/scripts/proxy.pac -u http://porteus-kiosk.org 2>/dev/null | tr -s ' ' | cut -d" " -f2 | sed 's/[^0-9a-zA-Z.:]*//g'`
    [ -n "$proxy" -a "$proxy" != DIRECT ] && sed -i 's_^proxy=DIRECT_proxy='$proxy'_g' /etc/profile.d/proxy.sh
    . /etc/profile.d/proxy.sh
fi

# Perform kiosk auto reconfiguration:
[ -e /opt/scripts/update-config ] && su -c /opt/scripts/update-config

# Perform kiosk auto update (paid subscription is required):
[ -e /opt/scripts/update ] && su -c /opt/scripts/update

# Start SSH daemon:
#ssh=yes
[ "$ssh" ] && /etc/rc.d/rc.sshd &

# Start VNC daemon:
#vnc=yes
[ "$vnc" ] && { killall -9 x11vnc; /etc/rc.d/rc.vncd & }

# Start tunnelling daemon providing direct access to kiosk from Porteus Kiosk Server:
#tunnel=yes
[ "$tunnel" ] && /usr/sbin/pktunnel &

# Run local commands which depends on the network availability:
for script in `ls -1 /etc/rc.d/local_net.d`; do . /etc/rc.d/local_net.d/$script; done

# Initialize printing:
#model=yes
if [ "$model" ]; then
    if [ -z "`pidof cupsd`" ]; then
	(
	cupsd
	#share_printer=yes
	[ "$share_printer" ] && cupsctl --share-printers
	sleep 3
	if echo "$model" | grep -q 'Raw Queue'; then
	    # Keep space after URI:
	    lpadmin -p kiosk-printer -E -v URI 
	elif echo "$model" | grep -q ' Foomatic/'; then
	    /usr/libexec/cups/driver/foomatic cat `grep "$model" /opt/scripts/files/wizard/printers.d/foomatic | cut -d'"' -f1 | head -n1` > /usr/share/ppd/kiosk.ppd
	    lpadmin -p kiosk-printer -E -v URI -m lsb/usr/kiosk.ppd
	else
	    lpadmin -p kiosk-printer -E -v URI -m `lpinfo --make-and-model "$model" -m | cut -d" " -f1 | head -n1`
	fi
	# Set kiosk-printer as default (needed for Chrome):
	lpoptions -d kiosk-printer
	# Default paper size:
	#paper_size=default
	[ "$paper_size" ] && sed -e 's|^*DefaultPageSize:.*|*DefaultPageSize: '"$paper_size"'|' -e 's|^*DefaultPageRegion:.*|*DefaultPageRegion: '"$paper_size"'|' -e 's|^*DefaultImageableArea:.*|*DefaultImageableArea: '"$paper_size"'|' -e 's|^*DefaultPaperDimension:.*|*DefaultPaperDimension: '"$paper_size"'|' -i /etc/cups/ppd/*.ppd
	) &
    fi
fi

# Scheduled actions:
[ -x /opt/scripts/scheduled-action ] && /opt/scripts/scheduled-action &

# RTC wake:
[ -x /opt/scripts/rtc-wake ] && /opt/scripts/rtc-wake &

# Enable Wake-On-LAN:
#ethtool -s `route -n | grep " UG " | head -n1 | rev | cut -d" " -f1 | rev` wol g

# Power saving tweaks:
if ! egrep -q -v '^Filename|^/dev/zram' /proc/swaps; then
    /opt/scripts/power_saver
fi

# Append MAC/hostname/PCID to the homepage:
#homepage_append=yes
if [ "$homepage_append" ]; then
    if [ "$homepage_append" = mac ]; then
	# Make sure the gateway is set so MAC address of the NIC used for network connection can be determined:
	GTW=`route -n | grep -c " UG "`; [ `route -n | grep -c -w ppp0` = 1 ] && GTW=1
	while [ $GTW -lt 1 ]; do sleep 1; GTW=`route -n | grep -c " UG "`; done
	MAC="$(cat /sys/class/net/`route -n | grep " UG " | head -n1 | rev | cut -d" " -f1 | rev`/address | sed s/://g | tr [a-z] [A-Z])"
	[ "$chrome" ] && { sed -i 's/?kiosk=mac/?kiosk='$MAC'/g' $json; sed -i 's/\&kiosk=mac/\&kiosk='$MAC'/g' $json; } || { sed -i 's/?kiosk=mac/?kiosk='$MAC'/g' $profile/prefs.js; sed -i 's/\&kiosk=mac/\&kiosk='$MAC'/g' $profile/prefs.js;  }
    elif [ "$homepage_append" = hostname ]; then
	[ "$chrome" ] && { sed -i 's/?kiosk=hostname/?kiosk='`hostname`'/g' $json; sed -i 's/\&kiosk=hostname/\&kiosk='`hostname`'/g' $json; } || { sed -i 's/?kiosk=hostname/?kiosk='`hostname`'/g' $profile/prefs.js; sed -i 's/\&kiosk=hostname/\&kiosk='`hostname`'/g' $profile/prefs.js; }
    elif [ "$homepage_append" = pcid ]; then
	[ "$chrome" ] && { sed -i 's/?kiosk=pcid/?kiosk='`grep ^ID: /etc/version | cut -d' ' -f2`'/g' $json; sed -i 's/\&kiosk=pcid/\&kiosk='`grep ^ID: /etc/version | cut -d' ' -f2`'/g' $json; } || { sed -i 's/?kiosk=pcid/?kiosk='`grep ^ID: /etc/version | cut -d' ' -f2`'/g' $profile/prefs.js; sed -i 's/\&kiosk=pcid/\&kiosk='`grep ^ID: /etc/version | cut -d' ' -f2`'/g' $profile/prefs.js; }
    fi
fi

# Homepage availability check:
#hcheck=yes
if [ "$hcheck" ]; then
    restart_net() {
    dunstify -u normal -i $PTH/status/dialog-warning.png "Restarting network service ..."
    killall dhcpcd wpa_supplicant 2>/dev/null
    for nic in `ls -1 /sys/class/net | grep -v ^lo`; do ifconfig $nic down; done
    killall dhcpcd wpa_supplicant 2>/dev/null
    sleep 3
    for nic in `ls -1 /sys/class/net | grep -v ^lo`; do ifconfig $nic up; done
    /etc/rc.d/rc.inet1; sleep 15
    }
    [ "$chrome" ] && hpage="`grep HomepageLocation $json | cut -d'"' -f4`" || hpage="`grep '"browser.startup.homepage"' $profile/prefs.js | cut -d'"' -f4 | cut -d'|' -f1`"
    CNUM=0
    while true; do
	test -e $hpage && break; dunstify -C 100 2>/dev/null
	if $wget -q -U Mozilla --spider -T20 -t1 "$hpage"; then
	    break
	else
	    let CNUM=CNUM+1; dunstify -r 100 -u critical -i $PTH/status/dialog-warning.png "$hcheck"
	    [ "$CNUM" = 60 ] && { restart_net; CNUM=0; }
	    sleep 9
	fi
    done
fi

# Managed bookmarks:
#bookmarks=yes
[ "$bookmarks" ] && /opt/scripts/managed-bookmarks

# Import certificates:
#icert=yes
if [ "$icert" ]; then
    /opt/scripts/import-certificates $icert
fi

# Screensaver slideshow:
#slideshow=yes
[ "$slideshow" ] && /opt/scripts/screensaver-slideshow "$slideshow"

# Browser preferences:
#brpref=yes
if [ "$brpref" ]; then
    # Setup proxy:
    if [ -e /opt/scripts/proxy.pac ]; then
	proxyc=`pactester -p /opt/scripts/proxy.pac -u $brpref | cut -d" " -f2-`
	[ "$proxyc" = DIRECT ] && unset http_proxy https_proxy ftp_proxy || export http_proxy="http://$proxyc" https_proxy="http://$proxyc" ftp_proxy="http://$proxyc"
    fi
    pkget $brpref /tmp/pref
    # Allow alphanumeric characters only:
    fromdos /tmp/pref 2>/dev/null; fromdos /tmp/pref 2>/dev/null; fromdos /tmp/pref 2>/dev/null; tr -dc "[:alnum:][:space:][:punct:]" < /tmp/pref > /tmp/prefs
    # Update browser preferences:
    if [ "$chrome" ]; then
	# Do not double preferences if session is restarted:
	test -e /opt/scripts/files/chrome.json && cp -a /opt/scripts/files/chrome.json $json || cp -a $json /opt/scripts/files
	tac $json 2>/dev/null | sed -n '/"/,$p' | tac > /tmp/json
	cat /tmp/prefs >> /tmp/json
	echo '}' >> /tmp/json
	mv -f /tmp/json $json
    else
	# Do not double preferences if session is restarted:
	test -e /opt/scripts/files/user.js && { cp -a /opt/scripts/files/user.js $profile; cp -a /opt/scripts/files/user.js $pprofile; } || cp -a $profile/user.js /opt/scripts/files 2>/dev/null
	cat /tmp/prefs >> $profile/user.js; cat /tmp/prefs >> $pprofile/user.js 2>/dev/null
    fi
    rm -f /tmp/pref /tmp/prefs
fi

# Enable support for removable devices:
#removable=yes
[ "$removable" ] && mv /sbin/udev-automount-disabled /sbin/udev-automount

# Toggle browser tabs:
#ttabs=yes
if [ "$ttabs" ]; then
    (
    sleep 20 # Wait till the browser is fully started
    toglec=$((`echo "$ttabs" | tr -dc '|' | wc -c`+2))
    toggle() { sleep `echo "$ttabs" | cut -d"=" -f2- | cut -d'|' -f $1`; xdotool key Ctrl+Tab; }
    while true; do
	RETRY=1
	while [ $RETRY -lt $toglec ]; do toggle $RETRY; let RETRY=RETRY+1; done
    done
    ) &
fi

# Refresh webpage:
#rpage=5
[ "$rpage" ] && ( while true; do sleep $rpage; xdotool key F5; done; ) &

# Delete unneeded utilities and logs:
rm -rf /tmp/log

# Preserve home directory:
cp -a /home/guest /opt/scripts

# Enable screensaver in case when no activity is detected:
#SSIDLE=300
[ "$SSIDLE" ] && /opt/scripts/screensaver-idle-watcher &

# Restart browser/session in case when no activity is detected:
#SIDLE=300
[ "$SIDLE" ] && /opt/scripts/session-idle-watcher &

# Booting is finished - start application:
/opt/scripts/gui-app &