#!/usr/bin/bash

if [ $(/usr/bin/id -u) != 0 ]; then echo "only root can do that"; exit 2; fi

##############################################################################
# This file is part of the CRYPTO BONE
# File     : cryptoboneexternd 
# Version  : 1.1.0 (external cryptobone)
# License  : BSD
# Date     : Tuesday, 1 November 2016
# Contact  : Please send enquiries and bug-reports to innovation@senderek.ie
#
# Copyright (c) 2015-2017
#	Ralf Senderek, Ireland.  All rights reserved. (https://senderek.ie)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. All advertising materials mentioning features or use of this software
#    must display the following acknowledgement:
#	   This product includes software developed by Ralf Senderek.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND  ANY EXPRESS OR 
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  IMPLIED WARRANTIES 
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.
##############################################################################

# Author:       Ralf Senderek <innovation@senderek.ie>
#
# license:      BSD
# description:  Activates the cryptobone daemon during the boot process 
# processname:  cryptoboneexternd 
# config:       none
# date:         1 November 2016
#

### BEGIN INIT INFO
# Provides:          cryptoboneexternd
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Activates the external cryptobone daemon
### END INIT INFO

# chkconfig:         2345  90 60

if [ -f /lib/lsb/init-functions ]
then
    . /lib/lsb/init-functions
fi 

##########################################################################

start() {

     # load the SELinux policy for the daemon
     if selinuxenabled ; then
          semodule -i /usr/lib/cryptobone/selinux/cryptobone.pp
          semodule -e cryptobone
     fi
     
     if [[  -L /usr/lib/cryptobone/ext/masterkey ]]; then
          if [[  -r /boot/master.key ]]; then
               # we need to remove the stored master key in the Beagle Bone boot partition
               echo "00000000000000000000000000000000000000000000000000" > /boot/master.key
               sync
               rm -f /boot/master.key /boot/cbb /boot/local.key
               sync
          fi
          if [[  -r /BOOT/master.key ]]; then
               # we need to remove the stored master key in the mounted memory key
               echo "00000000000000000000000000000000000000000000000000" > /BOOT/master.key
               sync
               rm -f /BOOT/master.key /BOOT/cbb /BOOT/local.key
               sync
          fi
	  # check, if there is an unmounted USB key with a master key to be deleted
	  BOOT=$(df | grep BOOT | cut -f1 -d' ')
	  if [[ x${BOOT} = "x" ]]; then
	      # find unmounted USB media
	      DEVLIST=$(ls /dev/sda[1-9] /dev/sdb[1-9] /dev/sdc[1-9] 2> /dev/null)
	      for DEV in ${DEVLIST}
	      do
	           if [[ -b $DEV ]]; then
		        LABEL=$(echo $(tune2fs -l $DEV 2>/dev/null | grep "volume name:" | cut -f2 -d':'))
			if [[ x${LABEL} != "x" ]]; then
			     if [[ $LABEL = "BOOT" ]]; then
		                  BOOT=$DEV
				  mount $DEV /mnt
                                  if [[  -r /mnt/master.key ]]; then
                                       echo "00000000000000000000000000000000000000000000000000" > /BOOT/master.key
                                       sync
                                       rm -f /mnt/master.key /mnt/cbb /mnt/local.key
                                       sync
                                  fi
				  umount /mnt
			     fi
		        fi
	           fi
              done
	 fi     
     fi
     
     # make sure that everything is up and running before daemon starts
     sleep 30
     # produce some entropy in the background
     find / 2> /dev/null > /dev/null &
     
     if [ ! -L /usr/lib/cryptobone/ext/masterkey ]; then
         # initialize database and create a master key and local key
         /usr/lib/cryptobone/ext/initialkeysetup
     fi
    
     # update firewall setup?
     if [[ -r /usr/lib/cryptobone/ext/init.d/usefirewall ]]; then
          systemctl stop firewalld
	  /usr/lib/cryptobone/ext/firewall red
     fi
     if grep cryptobone /etc/passwd >/dev/null 2>/dev/null; then
          echo "correct permissions after update"
          chown cryptobone /usr/lib/cryptobone /usr/lib/cryptobone/ext
          chown cryptobone /usr/lib/cryptobone/ext/cryptoboneshell
     fi
     # start the daemon
     rm -f /usr/lib/cryptobone/ext/secrets.sock
     /usr/lib/cryptobone/ext/cryptoboneexternd 
}


##########################################################################
stop() {
     if [ -d /dev/shm/EXRAM ]
     then
         /usr/lib/cryptobone/ext/bin/savemessages
     fi
     killall cryptoboneexternd
}


##########################################################################
case "$1" in
  start)
	start
	;;
  stop) 
	stop
	;;
  restart)
        echo "deliberately not implemented"
	;;
  status)
        echo "deliberately not implemented"
	;;
  force-reload)
        echo "deliberately not implemented"
        ;;
  *)
	echo "Usage: /usr/lib/cryptobone/ext/init.d/cryptoboneexternd {start|stop}"
	exit 1
esac

exit 0
