#!/usr/bin/env bash
set -euo pipefail

keyfile="/boot/crypto_key"
service="passless-boot_post_boot_cleanup.service"

cryptdevice="$(tr ' ' '\n' < /proc/cmdline | grep cryptdevice | tr ':' '\n' | grep cryptdevice | sed 's/^cryptdevice=//')"
if [[ "$cryptdevice" == "UUID="* ]]; then
  cryptdevice="/dev/disk/by-uuid/${cryptdevice#UUID=}"
fi

if [[ -b "$cryptdevice" ]]; then
  echo "✅ the current kernel was booted on cryptdevice $cryptdevice"
else
  echo "❌ failed to get the currently booted cryptdevice from /proc/cmdline:"
  cat /proc/cmdline
  echo "❌ this script only works with a cryptdevice=<device> option on the kernel command line"
  echo "   where <device> is a valid block device (or a  UUID=...)"
  exit 10
fi
if ! cryptsetup isLuks "$cryptdevice"; then
  echo "❌ the cryptdevice from the kernel commandline, $cryptdevice, is not a Luks encrypted drive."
  exit 20
fi

failure="FALSE"

if ! [[ -e "$keyfile" ]]; then
  echo "✅ keyfile $keyfile doesn't exist."
else
  echo "🕑 removing $keyfile from its slot in $cryptdevice luks header."
  if cryptsetup luksRemoveKey --key-file="$keyfile" "$cryptdevice"; then
    echo "✅ removed $keyfile to $cryptdevice."
  else
    echo "❌ failed to remove keyfile $keyfile from $cryptdevice"
    keyslot="$(\
      cryptsetup --verbose --key-file="$keyfile" --test-passphrase open "$cryptdevice" |\
      grep "Key slot [0-9] unlocked." | sed 's/Key slot //' | sed 's/ unlocked.//'\
    )"
    if [[ -n "$keyslot" ]]; then
      echo "🕑 removing $keyfile from its slot in $cryptdevice luks header."
      if cryptsetup luksKillSlot "$cryptdevice" "$keyslot"; then
        echo "✅ killed key slot $keyslot on $cryptdevice."
      else
        echo "❌ failed to remove key at slot $keyslot from $cryptdevice"
        echo "☢  the keyfile $keyfile is still valid, occupying slot $keyslot, for $cryptdevice"
        echo "☢  You need to cleanup the header yourself!"
	failure="TRUE"
      fi
    else
      echo "✅ no $keyslot is available for key $keyfile on $cryptdevice."
    fi
  fi

  echo "🕑 shredding $keyfile"
  shred -u "$keyfile"
  if [[ -e "$keyfile" ]]; then
    echo "❌ attempt to erase $keyfile failed."
    exit 10
  fi
  echo "✅ $keyfile erased."
  echo "🕑 running fstrim on $(dirname "$keyfile")"
  fstrim "$(dirname "$keyfile")"
fi

echo "🕑 disabling cleanup service $service"
systemctl disable "$service"
if [[ "$(systemctl is-enabled "$service")" == "disabled" ]]; then
  echo "✅ cleanup service disabled"
else
  echo "⚠  failed to disable cleanup service $service."
  exit 20
fi

if which rguard &>/dev/null; then
  echo "🕑 activating reboot-guard to prevent unwanted reboots."
  if rguard -1 --loglevel error; then
    echo "✅ reboot-guard activated: system protected from reboot."
  else
    echo "⚠  failed to activate reboot-guard"
    exit 30
  fi
fi

if [[ "$failure" == "TRUE" ]]; then
  echo "☢  FAILED TO REMOVE KEYFILE FROM LUKS HEADER."
  echo "☢  YOU HAVE SOME CLEANUP TO DO!!"
  exit 10
fi
echo "🎉 ALL DONE."

exit 0
