#!/usr/bin/env bash

# This script is used to enable OS drive encryption
# Reference https://confluence.zooxlabs.com/confluence/display/VS/Disk+Encryption+for+OS+Drive

exec >> /var/log/zooxpxeinstall.log 2>&1

echo 'create encryption key in kernel'

KEY_FOLDER="/etc/cryptroot"
KEY_FILENAME="keyfile"
KEY_FILE="${KEY_FOLDER}/${KEY_FILENAME}"

CRYPT_DISK=$(blkid -t TYPE="crypto_LUKS" | sed 's/:.*//g')
CRYPT_DISK_UUID=$(blkid -t TYPE="crypto_LUKS" | sed 's/.*UUID="\(.*\)" TYPE.*/\1/g')
CRYPT_MAPPER_DISK=$(blkid -t TYPE="LVM2_member" | sed 's/:.*//g'  | sed 's|.*/||g')
DISK_SERIALNUM=$(hdparm -I $CRYPT_DISK | grep "Serial Number:" | sed "s/.*://g" | sed "s/ //g")

PASSPHRASE="{{ cobbler_osdrive_encryption_default_password }}"
CRYPTTAB="/etc/crypttab"

if [ ! -d  "${KEY_FOLDER}" ]; then
     mkdir --parents "${KEY_FOLDER}"
fi

echo '#!/bin/sh
TRUE=0
FALSE=1

# flag tracking key-file availability
OPENED=$FALSE

if [[ -b /dev/usbdevice ]]; then
  # if device exists then output the keyfile from the usb key
  dd if=/dev/usbdevice bs=1 count=512 | cat
  OPENED=$TRUE
fi

if [[ $OPENED -ne $TRUE ]]; then
  echo "FAILED to get USB key file ..." >&2
  echo "read keyfile from kernel" >&2
  cat /etc/cryptroot/keyfile
else
  echo "Success loading key file from USB device. Moving on." >&2
fi
' > ${KEY_FOLDER}/getinitramfskey.sh

chmod +x /etc/cryptroot/getinitramfskey.sh

#create loadinitramfskey.sh
echo '#!/bin/sh
PREREQ=""
prereqs() {
  echo "$PREREQ"
}
case "$1" in
  prereqs)
    prereqs
    exit 0
    ;;
esac

. "${CONFDIR}/initramfs.conf"
. /usr/share/initramfs-tools/hook-functions

if [ ! -f "${DESTDIR}/lib/cryptsetup/scripts/getinitramfskey.sh" ]; then
    if [ ! -d "${DESTDIR}/lib/cryptsetup/scripts" ]; then
          mkdir --parents "${DESTDIR}/lib/cryptsetup/scripts"
    fi
    cp /etc/cryptroot/getinitramfskey.sh "${DESTDIR}/lib/cryptsetup/scripts/"
fi

if [ ! -d "${DESTDIR}/etc/cryptroot" ]; then
    mkdir --parents "${DESTDIR}/etc/cryptroot"
    cp /etc/cryptroot/keyfile "${DESTDIR}/etc/cryptroot/"
fi


' > ${KEY_FOLDER}/loadinitramfskey.sh
chmod +x ${KEY_FOLDER}/loadinitramfskey.sh

cp ${KEY_FOLDER}/loadinitramfskey.sh /usr/share/initramfs-tools/hooks/

dd if=/dev/urandom of=${KEY_FILE} bs=1 count=512
chmod 400 ${KEY_FILE}

echo "${CRYPT_MAPPER_DISK} UUID=${CRYPT_DISK_UUID} none luks,keyscript=/etc/cryptroot/getinitramfskey.sh" > ${CRYPTTAB}

update-initramfs -u
