# id - manage your CGA identity
#
# usage:
#   id              show your identity (handle + address)
#   id gen          mint a CGA keypair (refuses if one exists)
#   id set NAME     set your handle
#   id del          delete your keypair (asks to confirm)
#
# zrc parser notes (see project_zrc_parser_bugs):
#   - NO switch/case here: case bodies that redirect (> /dev/factotum/ctl)
#     and the multi-line nested ifs they need both mis-parse.  This is a
#     flat list of single-level `if (~ ...)` blocks instead.
#   - To branch on TWO things without nesting (the verb AND whether a key
#     exists), the two are joined with `^` into one token and matched with
#     `~` -- e.g. `$1^/^$key` is "gen/present" or "del/absent".

# Does a key already exist?  factotum's `genkey` silently overwrites, so
# `id gen` must guard against clobbering an existing identity.
key=absent
if (test -e /dev/factotum/key) { key=present }
confirm=no

# --- gen ---------------------------------------------------------------
if (~ $1^/^$key gen/present) {
    echo 'You already have an identity:'
    cat /dev/factotum/ctl
    echo 'Delete it first with:  id del'
    exit 1
}
if (~ $1^/^$key gen/absent) {
    echo 'Generating CGA keypair...'
    echo genkey > /dev/factotum/ctl
    cat /dev/factotum/ctl
    exit 0
}

# --- set ---------------------------------------------------------------
if (~ $1^/^$2 set/) {
    echo 'usage: id set NAME'
    exit 1
}
if (~ $1 set) {
    echo 'user '$2 > /dev/factotum/ctl
    echo 'user:' $2
    exit 0
}

# --- del ---------------------------------------------------------------
if (~ $1^/^$key del/absent) {
    echo 'No identity to delete.'
    exit 0
}
if (~ $1^/^$key del/present) {
    echo 'This permanently deletes your CGA identity:'
    cat /dev/factotum/ctl
    echo 'Type yes to confirm:'
    read confirm
    confirm=del^/^$confirm
}
if (~ $confirm del/yes) {
    echo delkey > /dev/factotum/ctl
    echo 'Identity deleted.'
    exit 0
}
if (~ $1^/^$key del/present) {
    echo 'Cancelled.'
    exit 0
}

# --- default: show identity -------------------------------------------
cat /dev/factotum/ctl
