#!/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"

        [ -e "${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}" | @SYSTEMD_REPLY_PASS@ 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.
    remaining_crypttab=$(clevis_devices_to_unlock) ||:
    remaining_askfiles=$(ls "${path}"/ask.* 2>/dev/null) ||:
    if [ -z "${remaining_crypttab}" ] && [ -z "${remaining_askfiles}" ]; then
        break;
    fi

    sleep 0.5
done
