#!/bin/bash
# -*- mode: sh; tab-width: 8; encoding: utf-8-unix -*-

prog=`basename $0 .bash`
PREFIX=/usr/local
ROLE=gpgkey
root=KeeC
DEBUG=1

. /usr/local/bin/usr_local_tput.bash
. /usr/local/bin/gridfire.rc
EXE=/var/local/bin/keepassxc-cli.bash

#? mayaybe not
if [ "$#" -eq 0 -o "$1" = '--help' ] ; then
    echo USAGE: $0 command [options]
    cat << EOF
Available commands:
analyze        Analyze passwords for weaknesses and problems.
clip           Copy an entry's attribute to the clipboard.
close          Close the currently opened database.
db-create      Create a new database.
db-info        Show a database's information.
diceware       Generate a new random diceware passphrase.
edit           Edit an entry.
estimate       Estimate the entropy of a password.
export         Exports the content of a database to standard output in the specified format.
generate       Generate a new random password.
help           Display command help.
import         Import the contents of an XML database.
locate         Find entries quickly.
ls             List database entries.
merge          Merge two databases.
mkdir          Adds a new group to a database.
mv             Moves an entry to a new group.
open           Open a database.
rm             Remove an entry from the database.
rmdir          Removes a group from a database.
show           Show an entry's information.

Options:
  -k, --key-file <path>           Key file of the database.
EOF
    exit 1
  fi

# [[ "$*" =~ "--pw-stdin" ]] || [[ $LARGS =~ "--pw-stdin" ]] || LARGS="--pw-stdin $LARGS"

if [[ "$*" =~ "db-create" ]] ; then
    [[ "$*" =~ "--decryption-time" ]] || [[ $RARGS =~ "--decryption-time" ]] || RARGS="--decryption-time=1000 $RARGS"
    # not =''
    #    [[ "$*" =~ "-k" ]] || [[ $RARGS =~ "-k" ]] || RARGS="-k '' $RARGS"

    [ -x $EXE ] || PANIC  file not found $EXE
    DBUG $EXE $LARGS $RARGS "$@" >> /tmp/${root}$$.log
    password=$(cat)
    /usr/bin/expect << EOF
# -*- mode: tcl; tab-width: 8; encoding: utf-8-unix -*-

set ROLE gpgkey
set PREFIX /usr/local

set timeout 30

spawn -noecho $EXE $LARGS $RARGS "$@"
log_user 0

expect "Enter password to encrypt database (optional):"
send   "$password\n"
expect   "Repeat password:"
send   "$password\n"

expect -re .+ {
    exp_continue
  } timeout {
    exit 1
  } eof {
    exit 0
  }
EOF
    retval=$?
    DBUG see /tmp/${root}$$.log
    exit $retval 
fi

DEBUG=1
DEBUG $EXE $LARGS $RARGS "$@" >> /tmp/${root}$$.log
$EXE $LARGS $RARGS "$@" 2>/tmp/${root}$$.err >>/tmp/${root}$$.log
retval=$?
if [ $retval  -eq 0 ] ; then
    INFO see /tmp/${root}$$.log
    cat /tmp/${root}$$.log
else
    WARN see /tmp/${root}$$.err /tmp/${root}$$.log
    cat /tmp/${root}$$.err
fi
exit $retval
