#!/bin/sh
PREREQ=""

prereqs()
{
        echo "$PREREQ"
}

case $1 in
prereqs)
        prereqs
        exit 0
        ;;
esac

cryptsetup tpmRecoveryUpdateFirst
# If we reached this stage, we do have a rootfs mounted
# so let's clean-up cryptroot setup mess...
autodecrypt="/cryptroot/autodecrypt"
#if [ ! -f "$autodecrypt" ] ; then
#	touch "$autodecrypt"
###fi
#echo "disk=/dev/sda1 mima=123456 type=1" >> "$autodecrypt"
#echo "mima=123456" > "$autodecrypt"
#echo "tpm_decrypt=1" >> "$autodecrypt"

#echo "disk=/dev/sda1" >> "$autodecrypt
if [ ! -f "$autodecrypt" ] ; then
	return 0
fi

while read -r line; do
    # 从每行中提取变量名和值
	echo "line:$line"
	if [ ! -n "$line" ]; then
        # 处理非空行
        break
    fi

    #IFS=" " read -r disk mima type <<< $line
    # 输出变量名和值
    
    disk=$(echo $line | awk -F ' ' '{print $1}')
    mima=$(echo $line | awk -F ' ' '{print $2}')
    type=$(echo $line | awk -F ' ' '{print $3}')
    CRYPTTAB_SOURCE=$(echo $disk | awk -F '=' '{print $2}')

    mima=$(echo $mima | awk -F '=' '{print $2}')

    tpm_decrypt=$(echo $type | awk -F '=' '{print $2}')
	
	LIBDIR=/root
    if [ -d ${LIBDIR}/usr/lib/ ] && [ -d "/lib" ]; then
           mount --bind ${LIBDIR}/usr/lib/ /lib
    fi
    plymouth quit
    while :
    do
        plymouth display-message --text="檢測到磁片'$CRYPTTAB_SOURCE'無法自動解密無法自動解密"
        /usr/bin/whiptail --title "自動解密配寘" --yesno "檢測到磁片$CRYPTTAB_SOURCE無法自動解密,是否需要更新自動解密金鑰?"  10 100
        result=$? 
        # `/lib/cryptsetup/askpass "檢測到磁片$CRYPTTAB_SOURCE無法自動解密,是否需要配寘自動解密？[y/n]"`
        if [ $result -eq 0 ]; then
            #/usr/bin/whiptail "您选择"是",正在更新" 
        	if [ $tpm_decrypt -ge 2 ]; then
                cryptsetup tpmPcrUpdate "$CRYPTTAB_SOURCE" --orig-pass "$mima" --noremoveorig 
            elif [ $tpm_decrypt -eq 1 ]; then
                cryptsetup tpmKm1KeyUpdate "$CRYPTTAB_SOURCE" --orig-pass "$mima"
            fi
            /usr/bin/whiptail --msgbox "配寘成功" 10 30
            break;
        elif [ $result -eq 1 ]; then
            /usr/bin/whiptail --msgbox "不进行配置" 10 30 
            break;
        else
            /usr/bin/whiptail "输入不对，重新选择"  
        fi
    done
done < "$autodecrypt"