#!/bin/sh
# decrypt_keyctl - to use in /etc/crypttab as keyscript
#  Allows to cache passwords for cryptdevices for 60s
#  The same password is used for for cryptdevices with the same identifier.
#  The keyfile parameter, which is the third field from /etc/crypttab, is
#  used as identifier in this keyscript.
#
# sample crypttab entries:
# test1   /dev/sda1    test_pw         luks,keyscript=decrypt_keytpm
# test2   /dev/sda2    test_pw         luks,keyscript=decrypt_keytpm
# test3   /dev/sda3    test_other_pw   luks,keyscript=decrypt_keytpm
#
#  test1 and test2 have the same identifier thus test2 does not need a password
#  typed in manually

ASKPASS_='/lib/cryptsetup/askpass'
lang_is_zh=false
lang_is_zhHk=false
lang_is_boCN=false
lang_is_mnMN=false

if [ -f /scripts/lang_is_zhHK ]; then
    lang_is_zhHK=true
elif [ -f /scripts/lang_is_boCN ]; then
    lang_is_boCN=true
elif [ -f /scripts/lang_is_mnMN ]; then
    lang_is_mnMN=true
elif [ -f /scripts/lang_is_zh ]; then
    lang_is_zh=true
fi
#diskUUID=`cryptsetup luksUUID $CRYPTTAB_SOURCE`
PROMPT_="請輸入密碼解鎖磁碟$CRYPTTAB_LABEL $CRYPTTAB_HOSTNAME： "

unseal_tpm(){
    cryptsetup getTpmKey
}

if [ -f ".tpm2-getkey${CRYPTTAB_NAME}.tmp" ];then
    $ASKPASS_ "$PROMPT_"
else
    touch ".tpm2-getkey${CRYPTTAB_NAME}.tmp"
    unseal_tpm
    result=$?
    if [ $result -eq 0 ]; then
        touch ".tpm2-getkey${CRYPTTAB_NAME}.error0"
    elif [ $result -eq 6 ]; then
        touch ".tpm2-getkey${CRYPTTAB_NAME}.error101"
    elif [ $result -eq 7 ]; then
        touch ".tpm2-getkey${CRYPTTAB_NAME}.error102"
    elif [ $result -eq 8 ]; then
        touch ".tpm2-getkey${CRYPTTAB_NAME}.error103"
    fi
fi