#!/bin/bash -e
# 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

shopt -s nullglob

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

while true; do
    todo=0

    for question in "$path"/ask.*; do
        unlocked=false
        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 [ -n "${device_uuid}" ]; then
            uuid="$(cryptsetup luksUUID "${d}")"
            [ "${uuid}" != "${device_uuid}" ] && todo=1 && continue
        fi

        if pt="$(clevis_luks_unlock_device "${d}")"; then
            echo -n "+$pt" | ncat -U -u --send-only "$s"
            unlocked=true
        fi

        [ -n "${device_uuid}" ] && [ "${unlocked}" == true ] && break
        [ "$unlocked" == true ] && continue
        ((todo++))
    done

    if [ -n "${device_uuid}" ]; then
        [ ! -b /dev/disk/by-uuid/"${device_uuid}" ] && break
        if clevis_is_luks_device_by_uuid_open "${device_uuid}"; then
            break
        fi
    fi

    if [ "$todo" -eq 0 ] || [ "$loop" != true ]; then
        break;
    fi

    sleep 0.5
done
