#!/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     : cbcontrol 
# Version  : 2.0 (EXTERNAL DEVICE)
# License  : BSD-3-Clause
# Date     : 25 May 2025
# Contact  : Please send enquiries and bug-reports to innovation@senderek.ie
#
# Copyright (c) 2015-2025
#	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.
##############################################################################

# This script executes all commands that have been received by the cryptoboneshell
# via the ssh tunnel from the clien machine.


. /usr/lib/cryptobone/ext/cbcontrol.functions
# DO NOT LOG $3
#-------------------------------------------------------------#

if [ ! -d /dev/shm/EXRAM ]
then
    /usr/lib/cryptobone/ext/rc.local
fi

date +%s > /dev/shm/EXRAM/GUI 2> /dev/null

if [ -L /usr/lib/cryptobone/ext/masterkey ]
then
     if [ "x$1" = "xEXIT" ]
     then
          echo "Bye for now."
          exit 0
     fi


     # check if EXTERN.local.key ($1) works, compare with sha256 hashvalue
     # exit "failed", if EXTERN.local.key is invalid 

     STOREDHASH=$(cat /usr/lib/cryptobone/ext/EXTERN.local.hash)
     EXTERNHASH=$(echo -n $1 | /usr/bin/sha256sum | /usr/bin/cut -c-64)
     if [[ ${STOREDHASH} != ${EXTERNHASH} ]];  then
          echo "failed: local authentication"
          exit 2
     fi

     shift

     # check if the daemon still waits for the transmission of the masterkey.
     # Once the database exists, the masterkey has been transferred and
     # /dev/shm/BOOT must be deleted

     if [ -d /dev/shm/BOOT  ] ; then
          # check if the daemon is still waiting or not
	  if [ -f /usr/lib/cryptobone/ext/database ] ; then
		# initialisation has already happened, and the masterkey
		# has been used to access the daemon
		/usr/bin/rm -rf /dev/shm/BOOT 2> /dev/null
	  fi
     fi


     if [ $# -ge 1 ]
     then
          case $1 in

          ATTACHMENT)   case $2 in
	                      LIST)             attachmentlist
			                        ;;

			      COPY)             copy_attachment "$3"
			                        ;;

			      DELETE)           delete_attachment "$3"
			                        ;;
                        esac
			;;

          CHECKWEBDROP) check_webdrop $2
                        ;;

          DEBUG)        /usr/bin/systemctl status cryptoboneexternd
                        ;;

          EXTERNAL)     case $2 in
                             STATUS)             check_external
                                                 ;;
                        esac     
                        ;;

          FETCH)        /usr/lib/cryptobone/systemd.fetch
                        ;;


          KEY)          case $2 in

			      NEWSECRETS) 	get_new_secrets
			                        ;;

			      RECIPIENTLIST)	recipient_list	
			                        ;;

			      RESET)		reset_key_for_email "$3"
			                        ;;

		 	      USE) 	        register_new_key "$3"  "$4"
			                        ;;

                              *) 	        echo "unknown KEY command"
			                        ;;

                        esac
                        ;;

	  MESSAGE)      case $2 in
			      COPY)             copy_message "$3"
                                                ;;
                        esac
	                ;;

          NETWORK) 	case $2 in
			      STATUS)	case $3 in
                                            CONNECT)  /usr/bin/sudo /sbin/ifconfig  2>&1
						      ;;
					    FIREWALL) /usr/bin/sudo /usr/lib/cryptobone/ext/firewall status
						      ;;
                                            PING)     /bin/ping -c1 -w1 $(cat /usr/lib/cryptobone/ext/pinghost)
                                                      ;;
                                        esac
			esac
                        ;;

          POWEROFF)     echo "going down"
			/usr/lib/cryptobone/ext/bin/cbb-poweroff 2>/dev/null
			;;
          
	  REBOOT)       echo "rebooting"
			/usr/lib/cryptobone/ext/bin/cbb-reboot 2>/dev/null
			;;
         
         
	  READ)	        case $2 in
			      DESTROY)		destroy_message $3
			                        ;;

			      MESSAGELIST)	get_message_list
			                        ;;
			              
                              MESSAGE)		read_message $3
			                        ;;
                             
                              WEBDROPLIST)      get_webdrop_list
                                                ;;

			      WEBDROP)		read_webdrop $3
			                        ;;



                        esac
			;;


          RESET)	echo "to destroy the masterkey and database use /bin/external-cryptobone destroy"
			;;

	  SETUP)        case $2 in
                             WID)	     get_wid ;;
			     WEBDROP)        show_safewebdrop_setup ;;
			     WEBDROPSECRET)  setup_safewebdropsecret "$3" ;;
			     WEBDROPSERVER)  setup_safewebdropserver  "$3" ;;
			     WEBDROPUSER)    setup_safewebdropuser "$3" ;;
			     CLEARREG)       setup_clear_safewebdrop_registration ;;
			     REGISTER)       setup_register_safewebdrop ;;
			     REGISTRATION)   setup_get_safewebdrop_registration ;;
			esac
			;;


          STATUS)       RES=$(echo "get-element cryptobone" | socat -t15 - UNIX-connect:$SOCK 2> /dev/null)
			if [[ x${RES} != "x" ]]; then
			     echo "active"
		        else 
			     echo "waiting"
		        fi
		        ;;

	  SYSTEM)       case $2 in
	                     SUSPEND)    cryptobonesuspend ;;
			     RESUME)     cryptoboneresume ;;
			     POWEROFF)   clear_RAM ;;
			     RESTART)    /usr/lib/cryptobone/ext/rc.local ;;
			     UPLOAD)     echo "$3" | socat -d -t15 - UNIX-connect:$SOCK 2>&1 ;;
			esac
			;;


          WEBDROP)      safewebdrop_message "$2"  "$3" "$4"
			;;


          *)            echo "failed"
		        ;;
         esac
         exit 0
     fi
     echo "failed"
     exit 1
fi
#-------------------------------------------------------#
