#!/bin/bash
#
# Copyright (c) 2024 Oldřich Jedlička
#
# Author: Oldřich Jedlička <oldium.pro@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

. /lib/dracut-crypt-lib.sh
. clevis-luks-common-functions

mkdir -p /run/cryptroot-ask-pipes
chmod 0700 /run/cryptroot-ask-pipes

pipeprefix=run/cryptroot-ask-pipes
ensurestarted=0

# shellcheck disable=SC2154 # $hookdir is a dracut variable
for askpass in "$hookdir"/initqueue/settled/cryptroot-ask-*.sh; do
    [ ! -e "${askpass}" ] && continue

    if device=$(grep '^[^ ]*/cryptroot-ask ' "${askpass}" | awk '{print $2}'); then
        if [ "${1##/dev/dm-}" != "$1" ]; then
            device="/dev/mapper/$(dmsetup info -c --noheadings -o name "$1")"
        fi

        getkey /tmp/luks.keys "$device" >/dev/null && continue

        detectedfile="/tmp/clevis-device-detected-${device//\//_}"
        [ -f "${detectedfile}" ] && continue
        : >> "${detectedfile}"

        pins=$(clevis_luks_read_used_pins "${device}") || continue

        if [[ " $pins " == *" tang "* ]] && getargbool 0 rd.neednet && [ ! -f /run/clevis-online ]; then
            mv -f "${askpass}" "${askpass/settled/online}"
        fi

        pipepath="${pipeprefix}/pipe-${device//\//_}"
        echo "rd.luks.key=/:${pipepath}:${device}" >> /etc/cmdline.d/60-clevis-keys.conf
        echo "${device}:/:${pipepath}" >> /tmp/luks.keys
        mkfifo "/${pipepath}"
        ensurestarted=1
    fi
done

[ $ensurestarted -eq 1 ] && [ ! -s /run/clevis.pid ] && /bin/clevis-password-unlocker
