#!/bin/sh -e

readonly conf_dir="${conf_dir:-$HOME/.config/kanako}"
readonly key_dir="${key_dir:-$HOME/.kanako}"
readonly store_dir="${store_dir:-$HOME/.kanako-store}"

if test -d "${store_dir}"; then
    cd "${store_dir}"
else
    echo "Password store not found!"
    echo "Create it with `mkdir -p $store_dir`"
    exit 1
fi

if test -f "${conf_dir}/kanako.conf"; then
    . "${conf_dir}/kanako.conf";
else
    echo "Configuration file has not been found!"
    echo "Copy kanako.conf from the examples directory,"
    echo "and edit accordingly."
    exit 1
fi

fn_copy() {
    fn_view $1 | "${clip_cmd}"
}
fn_edit() {
    ${encrypt_cmd} ${decrypt_args} ${1%%.enc}.enc > ${1%%.enc}
    "${EDITOR}" "${1%%.enc}"
    ${encrypt_cmd} ${encrypt_args} ${1%%.enc} > ${1%%.enc}.enc
    rm "${1%%.enc}"
}
fn_list() {
    "${list_cmd}" "${store_dir}"
}
fn_new() {
    test -d $1 && fn_usage && exit 1

    tmpfile="$(mktemp)"
    "${EDITOR}" "${tmpfile}"

    mkdir -p "$(dirname "$1")"
    ${encrypt_cmd} ${encrypt_args} ${tmpfile} > ${1%%.enc}.enc
    rm ${tmpfile}
}
fn_trash_directory() {
    rm -rf $@
}
fn_trash_entry() {
    rm -f "${1}${2}".enc
}
fn_usage() {
    cat <<EOF
Usage:
kanako [-celnrRv] <arguments>
EOF
}
fn_view() {
    if [ -f "${1%%.enc}".enc ]; then
	${encrypt_cmd} ${decrypt_args} "${1%%.enc}".enc
    elif [ -d "${1:-.}" ]; then
	${list_cmd} "${1:-.}"
    else
	fn_usage
    fi   
}

case $1 in
    -c) fn_copy $2 ;;
    -e) fn_edit $2 ;;
    -l) fn_list ;;
    -n) fn_new $2 ;;
    -r) fn_trash_entry $2 ;;
    -R) fn_trash_directory $2 ;;
    -v) fn_view $2 ;;
    *) fn_usage ;;
esac
