#!/usr/bin/bash


#
# Copyright 2014-2024 Senderek Web Security, Ireland. All rights reserved.
#                <https://senderek.ie/opensource/secureboot2>
#
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

#
# Author:       Ralf Senderek <innovation@senderek.ie>
#
# license:      GNU General Public License version 3 or later
# description:  changes the passphrase on a copy of an encrypted filesystem
# processname:  secureboot-backup 
# config:       none
# date:         7/5/2024
#


ROOT=/usr/lib/secureboot
BACKDIR=$ROOT/backup
FILE=$ROOT/securefilesystem
DATE=$(date +%Y-%m-%d)
BACK=$BACKDIR/securefilesystem-$DATE
RET=0
ACTIVE="no"

NAME=secure

checkspace() {
     echo "Checking for required disk space ..."
     BLOCKS=$(df -k /| grep dev)
     FREEBLOCKS=$(echo $BLOCKS | cut -f4 -d" ")
     NEWBLOCKS=$(du $FILE| cut -f1 -d"/")
     NEWBLOCKS=$(expr $(echo -n $NEWBLOCKS) + 1000 )
     echo "$FREEBLOCKS blocks available, $NEWBLOCKS needed."
     echo
     if [ $NEWBLOCKS -gt $FREEBLOCKS ]; then
	   return 2 
     fi	 
     return 0
}

if [  -b /dev/mapper/$NAME ]; then
     /usr/lib/secureboot/secureboot2 stop
     if [ $? != 0 ] ; then
          echo "Cannot stop the busy secure filesystem. Exiting ..."
	  echo "If you have user home directories in /secure you cannot create"
	  echo "a backup while users are logged in."
	  echo "Please go into single user mode first."
	  echo "You can use the following commands as root."
	  echo "All other users are logged out."
	  echo
	  echo "init 1"
	  echo "/usr/lib/secureboot/secureboot-backup"
	  echo "init 5"
	  echo
          exit 3
     else
          ACTIVE="yes"
     fi
fi

# secure filesystem is stopped

if [ $# -gt 0 ]; then
     echo "usage: secureboot-backup"
     if [ $ACTIVE = "yes" ]; then
          /usr/lib/secureboot/secureboot2 start
     fi
     RET=2
else
     echo "CREATING A BACKUP ..."
     echo
     checkspace
     if [ $? = 0 ]
     then
          echo "Copying, please be patient ..."
          [ ! -d $BACKDIR ] && mkdir $BACKDIR
          cp $FILE $BACK
          ls -l $BACK
	  RET=0
          echo
     else
          echo "Not enough space for a backup. Exiting ..."
	  exit 2
     fi	  
fi
if [ $ACTIVE = "yes" ]; then
      /usr/lib/secureboot/secureboot2 start
fi
exit $RET
#################################################################

