#!/bin/bash
set -eu
# vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80:
#
# Copyright (c) 2016 Red Hat, Inc.
# Author: Harald Hoyer <harald@redhat.com>
# Author: Nathaniel McCallum <npmccallum@redhat.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/>.
#

. clevis-luks-common-functions

# Make sure to exit cleanly if SIGTERM is received.
trap 'echo "Exiting due to SIGTERM" && exit 0' TERM

loop=
path=/run/systemd/ask-password
while getopts ":lp:" o; do
    case "${o}" in
    l) loop=true;;
    p) path="${OPTARG}";;
    *) ;;
    esac
done

while true; do
    for question in "${path}"/ask.*; do
        # question will expand to itself, in case no files match, so we verify
        # whether it actually exists, before proceeding.
        [ ! -e "${question}" ] && continue

        d=
        s=
        while read -r line; do
            case "$line" in
                Id=cryptsetup:*) d="${line##Id=cryptsetup:}";;
                Socket=*) s="${line##Socket=}";;
            esac
        done < "$question"

        [ -b "${d}" ] || continue
        [ -S "${s}" ] || continue

        if ! pt="$(clevis_luks_unlock_device "${d}")" || [ -z "${pt}" ]; then
            continue
        fi

        uuid="$(cryptsetup luksUUID "${d}")"
        if ! printf '%s' "${pt}" | /usr/lib/systemd/systemd-reply-password 1 "${s}"; then
            echo "Unable to unlock ${d} (UUID=${uuid}) with recovered passphrase" >&2
            continue
        fi

        echo "Unlocked ${d} (UUID=${uuid}) successfully" >&2
    done

    [ "${loop}" != true ] && break
    # Checking for pending devices to be unlocked.
    if remaining=$(clevis_devices_to_unlock) && [ -z "${remaining}" ]; then
        break;
    fi

    sleep 0.5
done
