#!/bin/sh
# $YakumoLabs: kanako,v 2.3 2025/05/14 02:07:06 yakumo_izuru Exp $

kanako_conf_dir="${kanako_conf_dir:-$HOME/.config/kanako}"
kanako_key_dir="${kanako_key_dir:-$HOME/.kanako}"
kanako_store_dir="${kanako_store_dir:-$HOME/.kanako-store}"

_die() {
	printf "\033[0;31m%s\033[0m\n" "$*" >&2
	exit 1
}
_info() {
	printf "\033[0;32m%s\033[0m\n" "$*"
}
_warn() {
	printf "\033[0;33m%s\033[0m\n" "$*"
}

[ -d "${kanako_store_dir}" ] && cd "${kanako_store_dir}" || _die "Password store not found"
[ -f "${kanako_conf_dir}/kanako.conf" ] && . "${kanako_conf_dir}/kanako.conf" || _die "Configuration file not found"

copy() {
	view "$1" | "${kanako_clip_cmd}"
}
edit() {
	if [ -f ${1%%.enc}.enc ]; then
		${kanako_encrypt_cmd} ${kanako_decrypt_args} ${1%%.enc}.enc >${1%%.enc}
		"${EDITOR:-${EDITOR:-vi}}" "${1%%.enc}"
		${kanako_encrypt_cmd} ${kanako_encrypt_args} ${1%%.enc} >${1%%.enc}.enc
		rm "${1%%.enc}"
	else
		_warn "${1%%.enc}.enc does not exist, maybe there was a typo on your end?"
	fi
}
gen() {
	printf "%s\n" $(strings </dev/urandom | dd bs=1 count="${1:-30}" 2>/dev/null | tr -d ' \t\n\r')
}
list() {
	if [ -z "$(command -v tree)" ]; then
		_die "Required dependency 'tree' not found"

	fi
	if [ -z "$1" ]; then
		tree "${kanako_store_dir}/" | sed 's/\.enc//g'
	else
		tree "${1:-.}" | sed 's/\.enc//g'
	fi
}
new() {
	[ -d "$1" ] && usage
	tmpfile="$(mktemp)"
	"${EDITOR:-${EDITOR:-vi}}" "${tmpfile}"
	mkdir -p "$(dirname "$1")"
	${kanako_encrypt_cmd} ${kanako_encrypt_args} ${tmpfile} >${1%%.enc}.enc
	rm ${tmpfile}
}
otp() {
	if [ -z "$(command -v oathtool)" ]; then
		_die "Required dependency 'oathtool' not found"
	fi
	totp_seed=$(view "$1" | grep 'totp: ' | head -n1 | cut -d' ' -f2)
	if ! [ -z ${totp_seed} ]; then
		oathtool --totp -b ${totp_seed}
	fi
}
delete_directory() {
	_warn "Will be removing $1"
	_warn "Are you okay with that?"
	read junk
	case ${junk} in
		n | N) _info "Abort" ;;
		y | Y) rm -rf "${1}" && _info "Removed $1" ;;
	esac
}
delete_file() {
	_warn "Will be removing $1"
	_warn "Are you okay with that?"
	read junk
	case ${junk} in
		n | N) _info "Abort" ;;
		y | Y) rm -f "${1}.enc" && _info "Removed $1/$2" ;;
	esac
}
usage() {
	_info "Usage: kanako [-ceglnorRv] args"
	_info "The arguments for all switches are relative to \${kanako_store_dir}"
	_info "which is located at ${kanako_store_dir}"
	exit
}
view() {
	if [ -f "${1%%.enc}".enc ]; then
		${kanako_encrypt_cmd} ${kanako_decrypt_args} "${1%%.enc}".enc
	else
		_die "${1%%.enc} was not found"
	fi
}

cmd="$1"
arg="$2"

case ${cmd} in
	-c) copy ${arg} ;;
	-e) edit ${arg} ;;
	-g) gen ${arg} ;;
	-h) usage ;;
	-l) list ${arg} ;;
	-n) new ${arg} ;;
	-o) otp ${arg} ;;
	-r) delete_file ${arg} ;;
	-R) delete_directory ${arg} ;;
	-v) view ${arg} ;;
	*) usage ;;
esac
