#!/bin/sh

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

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

################################################################################
# const
trigger_file="/root/do_luks_unlocking"

################################################################################
# var

################################################################################
# helper functions

# function to detect the start trigger
wait_for_start_trigger() {
  local max_waitining_time_seconds=60
  local waiting_time_seconds=5
  local waited_time_seconds=0
  while { test ! -r ${trigger_file} && test ${waited_time_seconds} -le ${max_waitining_time_seconds} ; } ; do
    # if the file is not existing or the script is not waiting too much.
    sleep ${waiting_time_seconds}
      #wait 5 seconds.
    let waited_time_seconds+=${waiting_time_seconds}
  done
  
  if test ! ${waited_time_seconds} -le ${max_waitining_time_seconds} ; then
    echo "waited to much for the do_luks_unlocking trigger"
    exit 0
  fi
  
  if test -r ${trigger_file} ; then
    # the script consume the trigger (for the next iteration)
    rm ${trigger_file}
  fi
  
  sleep 5 # waiting the cryptsetup askpass to spawn.
}

# function to detect an early exit.
check_if_should_end() {
  if test ! -r "/root/do_luks_unlocking" ; then
    # if the file is not existing
    echo "no do_luks_unlocking, exit"
    exit 0
  fi
}

################################################################################
# check if the passhphrases are available.
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}")

################################################################################
#unlocking procedure.
for luks_passphrase in ${luks_passphrases}; do
  # try to open with one passphrase each time.  
  wait_for_start_trigger
  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.  


