#!/bin/sh

# Source function library
. /etc/init.d/functions

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/legato/systems/current/bin
DESC=Legato

set -e

case $1 in
  start)
	echo -n "Starting $DESC: "
	if [ -e /opt/legato/legato.squashfs ];then
		mount /opt/legato/legato.squashfs /mnt/legato
		if [ -x /mnt/legato/start ];then
			if [ ! -d /tmp/legato ];then
				mkdir /tmp/legato
			fi;
#			touch /tmp/legato/.DEBUG_NO_REBOOT

			if [ ! -d /home/root/.ssh ];then
				mkdir /home/root/.ssh
				chmod 700 /home/root/.ssh
        		fi;
			if [ ! -s /home/root/.ssh/authorized_keys ];then
				if [ -e /home/root/.ssh/authorized_keys ];then
					rm /home/root/.ssh/authorized_keys
				fi;
				if [ -d /mnt/flash/home/root ];then
					cp /mnt/flash/home/root/.ssh/authorized_keys /home/root/.ssh/authorized_keys
					chmod 600 /home/root/.ssh/authorized_keys
				fi;
			fi;
			if [ -d /mnt/flash/home/root ];then
				if ! diff /mnt/legato/apps/*/read-only/ssh/authorized_keys /home/root/.ssh/authorized_keys >/dev/null 2>&1;then
					cp /mnt/flash/home/root/.ssh/authorized_keys /home/root/.ssh/authorized_keys
					chmod 600 /home/root/.ssh/authorized_keys
				fi
			fi;
			if [ -e /lib/ld-linux-armhf.so.3 ] && [ ! -e /lib/ld-linux.so.3 ];then
				ln -s $(readlink /lib/ld-linux-armhf.so.3) /lib/ld-linux.so.3
			fi;

			if ! /sbin/ldconfig -p |/bin/grep liblegato.so >/dev/null 2>&1;then
				/sbin/ldconfig
			fi;

			if [ ! -d /mnt/flash/legato/smack ];then
				mkdir -p /mnt/flash/legato/smack
			fi;

			#Start the legato framework
			/mnt/legato/start > /dev/null 2>&1

			if ! /sbin/ldconfig -p |/bin/grep liblegato.so >/dev/null 2>&1;then
				/sbin/ldconfig
			fi;
		fi;
	fi;
	if [ ! -d /home/root/.ssh ];then
		mkdir /home/root/.ssh
		chmod 700 /home/root/.ssh
        fi;
	if [ -e /var/cache/dnf/metadata_lock.pid ];then
		rm /var/cache/dnf/metadata_lock.pid
	fi;
	if [ ! -s /home/root/.ssh/authorized_keys ];then
		if [ -e /home/root/.ssh/authorized_keys ];then
			rm /home/root/.ssh/authorized_keys
		fi;
		cp /legato/systems/current/apps/combapp/read-only/ssh/authorized_keys /home/root/.ssh/authorized_keys
		chmod 600 /home/root/.ssh/authorized_keys
	fi;
	if ! diff /legato/systems/current/apps/combapp/read-only/ssh/authorized_keys /home/root/.ssh/authorized_keys >/dev/null 2>&1;then
		cp /legato/systems/current/apps/combapp/read-only/ssh/authorized_keys /home/root/.ssh/authorized_keys
		chmod 600 /home/root/.ssh/authorized_keys
	fi;
  ;;
  stop)
	echo -n "Stopping $DESC: "
	if [ -x /legato/systems/current/bin/start ];then
		/legato/systems/current/bin/start stop
		sleep 2
	fi;

	if [ -e /mnt/legato/start ];then
 		umount /mnt/legato
	fi;

	if [ -d /legato/smack ];then
		umount /legato/smack
	fi;

	if [ -d /legato ];then
		umount /legato
	fi;
  ;;
  restart|force-reload)
	$0 stop
	sleep 1
	$0 start
  ;;
  status)
	status ${DAEMON} || exit $?
   ;;
   *)
	N=/etc/init.d/legato
	echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
