#!/bin/sh -e

conf_dir=${conf_dir:-$HOME/.config/ayu}
key_dir=${key_dir:-$HOME/.ayu}
store_dir=${store_dir:-$HOME/.ayu-store}

cd ${store_dir} || exit 1

. ${conf_dir}/config

fn_copy() {
    fn_view $2 | ${clip}
}
fn_edit() {
    ${decrypt_cmd} ${decrypt_args} ${1%%.enc}.enc
    ${EDITOR} ${1%%.enc}
    ${encrypt_cmd} ${encrypt_args} ${1%%.enc}
    rm ${1%%.enc}
}
fn_generate() {
    pwgen -s ${2:-80}
}
fn_list() {
    if command -v tree 2>/dev/null; then
	tree ${store_dir}
    else
	ls -l ${store_dir}
    fi
}
fn_new() {
    test -d $1 && fn_usage && exit 1

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

    mkdir -p $(dirname $1)
    ${encrypt_cmd} ${encrypt_args} ${tmpfile}

    mv ${tmpfile}.enc ${1%%.enc}.enc
    rm ${tmpfile}
}
fn_trash_directory() {
    rm -rf $@
}
fn_trash_entry() {
    rm -f ${1}${2},enc
}
fn_usage() {
    cat <<EOF
Usage:
ayu [-ceglnrRv] <arguments>
ayu [copy|edit|generate|list|add|trash|trashdir|view] <arguments>
EOF
}

case $1 in
    -c | copy) fn_copy $2 ;;
    -e | edit) fn_edit $2 ;;
    -g | generate) fn_generate $2 ;;
    -l | list) fn_list ;;
    -n | add) fn_new ;;
    -r | trash) fn_trash $2 ;;
    -R | trashd) fn_trash_directory $2 ;;
    -v | view) fn_view $2 ;;
    *) fn_usage ;;
esac
