#!/usr/bin/env bash

# rofi-ykman
# YubiKey OATH utility

#2019 nukeop

print_usage() {
    echo "Usage: rofi-ykman [command]"
    echo
    echo "Commands:"
    echo "  clipboard   Copy the code to the clipboard. (default)"
    echo "  type        Type the code."
    echo
}

clipboard () {
    if [ $XDG_SESSION_TYPE == "wayland" ]
    then
        wl-copy
    else
        xsel --clipboard
    fi
}

type () {
    if [ $XDG_SESSION_TYPE == "wayland" ]
    then
        wtype -
    else
        xargs xdotool type
    fi
}

# shortcuts
type="Alt+1"
clipboard="Alt+2"

main() {
    accounts=$(ykman oath accounts list)

    shortcuts=(
        -kb-custom-1 "$type"
        -kb-custom-2 "$clipboard"
    )
    prompt="YubiKey OATH"

    account=$(echo "${accounts/, TOTP/\n}" | awk '{ print $0 "\0icon\x1fyubioath"; }' | rofi -dmenu -i -p "$prompt" ${shortcuts[@]})
    case $? in
        1) exit ;;
        10) command=type ;;
        11) command=clipboard ;;
        *) command=$default_command ;;
    esac

    code=$(ykman oath accounts code "$account")
    IFS=', ' read -r -a code <<< "$code"

    case $command in
        clipboard) echo -n "${code[-1]}" | wl-copy;;
        type) echo -n "${code[-1]}" | type;;
    esac
}

default_command="${1:-type}"

case $default_command in
    clipboard|type) ;;
    *) print_usage; exit 1;;
esac

main
