#!/usr/bin/sh

command -v getargbool > /dev/null || . /lib/dracut-lib.sh

generator_set_device_timeout() {
    local _name
    local _timeout="$2"

    _name=$(dev_unit_name "$1")

    if ! [ -f "$GENERATOR_DIR"/"${_name}".device.d/timeout.conf ]; then
        mkdir -p "$GENERATOR_DIR"/"${_name}".device.d
        {
            echo "# Automatically generated by ${0##*/}"
            echo
            echo "[Unit]"
            echo "JobTimeoutSec=$_timeout"
            echo "JobRunningTimeoutSec=$_timeout"
        } > "$GENERATOR_DIR"/"${_name}".device.d/timeout.conf
    fi
}

if ! getargbool 1 rd.luks; then
    # crypto LUKS detection is disabled
    return 0
fi

[ -e /etc/crypttab ] || return 0

GENERATOR_DIR="$1"
[ -n "$GENERATOR_DIR" ] || return 1
[ -d "$GENERATOR_DIR" ] || mkdir -p "$GENERATOR_DIR"

timeout=$(getarg rd.timeout)
timeout=${timeout:-infinity}
while read -r _ _source_device _ || [ -n "$_source_device" ]; do
    _dev=$(label_uuid_to_dev "$_source_device")
    generator_set_device_timeout "$_dev" "$timeout"
done < /etc/crypttab
