#!/bin/sh

# { Notes
# - Script called by scripts/local-top/cryptroot

# { Arguments
# /root/luks_passhphrases
#    luks passphraseS as file.

# function to detect an early exit.
should_it_terminate() {
  if test ! -r "/root/DO_LUKS_UNLOCKING" ; then
    # if the variable is not set (i.e: empty) or
    # the variable is false
    # we should exit.
    echo "no DO_LUKS_UNLOCKING, exit"
    exit 0
  fi
}

luks_passhphrases_file="/root/luks_passhphrases"
if test ! -r "${luks_passhphrases_file}" || test $(cat "${luks_passhphrases_file}" | wc -c ) -eq 0 ; then
  echo "No passhphrases caught, exit"
  exit 0
fi
luks_passphrases=$(cat "${luks_passhphrases_file}")

sleep 2 # initial wait

last_opening_device_path=""
  
for luks_passphrase in ${luks_passphrases}; do
  while test $(ps | grep -i -c "cryptsetup.*luksopen") -le 1 ; do
    # checking for the process that uses the passphrase. Until it spawns
    sleep 1
    should_it_terminate
  done
  
  opening_device_path=$(ps | grep -i -m 1 "cryptsetup.*luksopen" | grep -i -o "/dev[^ ]*")
  if test -z ${last_opening_device_path} ; then
    # if it is the first time.
    last_opening_device_path="${opening_device_path}"
  elif test "${opening_device_path}" != "${last_opening_device_path}" ; then
    # if the device is changed (we opened the previous one hopefully)
    break # we need to restart the trials
  fi
  
  should_it_terminate
  
  # opening as soon the process is ready.
  echo -n "${luks_passphrase}" > /lib/cryptsetup/passfifo
  
  echo "wait some time for the cryptsetup decoding the key."
  sleep 5
done
  
# if all the passphrases were tried, since this script
# is called by the main script that setup the luks opening,
# then we can say either that the device was opened or that a human
# intervention is needed. Because in the worst case all
# the passphrases are tried on the same device and were not working.  


