recovery_units=(fprintd.service kait2en-t2-touchid.service)
recovery_guard=$'[Service]\nExecCondition=+/usr/bin/flock -n -E 1 /run/t2-keybag-trial.lock /usr/bin/true'
restart_units=()
guard_files=()

wait_touchid_protocol() {
    local bridge=kait2en-t2-touchid.service invocation
    local deadline=$((SECONDS + 30))
    while (( SECONDS < deadline )); do
        if systemctl is-active --quiet "$bridge" &&
            invocation=$(systemctl show "$bridge" --property=InvocationID --value) &&
            [[ -n $invocation && -n $(journalctl -q -b -u "$bridge" -o cat -n 1 \
                "_SYSTEMD_INVOCATION_ID=$invocation" \
                --grep='^t2-touchid: Touch ID recovery lockout protocol uid-v1$') ]] &&
            [[ $(systemctl show "$bridge" --property=InvocationID --value) == "$invocation" ]] &&
            systemctl is-active --quiet "$bridge"; then
            return 0
        fi
        sleep 1
    done
    return 1
}

clear_touchid_guards() {
    local unit file
    # Call with the operation lock held. An interrupted process can leave
    # its guards installed, but no other live operation can still own them.
    for unit in "${recovery_units[@]}"; do
        file=/run/systemd/system/$unit.d/90-t2-touchid-recovery.conf
        if [[ -f $file && ! -L $file && $(<"$file") == "$recovery_guard" ]]; then
            rm -- "$file" || return 1
        fi
    done
    systemctl daemon-reload
}

pause_touchid() {
    local unit directory file

    for unit in "${recovery_units[@]}"; do
        if systemctl is-active --quiet "$unit"; then restart_units+=("$unit"); fi
        directory=/run/systemd/system/$unit.d
        file=$directory/90-t2-touchid-recovery.conf
        mkdir -p -- "$directory"
        if [[ -e $file || -L $file ]]; then
            [[ -f $file && ! -L $file && $(<"$file") == "$recovery_guard" ]] || return 1
            guard_files+=("$file")
        else
            guard_files+=("$file")
            printf '%s\n' "$recovery_guard" >"$file"
        fi
    done

    # D-Bus can start fprintd again after a stop. The runtime condition keeps
    # both services out of the SEP until the lock is released.
    systemctl daemon-reload
    systemctl stop "${recovery_units[@]}"
}

resume_touchid() {
    local result=0
    if (( ${#guard_files[@]} )); then
        rm -f -- "${guard_files[@]}" || result=1
        systemctl daemon-reload || result=1
    fi
    if (( ${#restart_units[@]} )); then
        systemctl start "${restart_units[@]}" || result=1
    fi
    return "$result"
}
