#!/usr/bin/env bash

command -v nc >/dev/null || { echo >&2 "Netcat not installed. Aborting."; exit 1; }

echo OK Your orders please

while IFS="\n" read -r command; do
    if [ "$command" == "GETINFO flavor" ]; then
        echo D stumpwm
    elif [[ "$command" == SETDESC* ]]; then
        description=${command:8}
    elif [[ "$command" == SETPROMPT* ]]; then
        prompt=${command:10}
    elif [ "$command" == GETPIN ]; then
        password=$(stumpish eval "(pinentry:getpin \"$description\" \"$prompt\")" | cut -d '""' -f 2)
        if [ -z "$password" ]; then
            echo S close_button
        fi
        echo D "$password"
    elif [ "$command" == BYE ]; then
        exit 0
    fi
    echo OK
done < /dev/stdin
