#!/bin/mksh
# Interactive mksh configuration
# Source login profile if not already loaded
[ -z "$EDITOR" ] && . "$HOME/.profile"
# Vi mode
set -o vi
# Prompt: user@host:dir >
PS1='$(print -n "\033[34m")${USER}$(print -n "\033[0m")@$(print -n "\033[35m")$(hostname -s)$(print -n "\033[0m"):$(print -n "\033[36m")${PWD/#$HOME/\~}$(print -n "\033[0m") > '
# History
HISTFILE="$HOME/.mksh_history"
HISTSIZE=10000
# Source config modules
. "$HOME/.config/.mksh/load.sh"
# Zoxide (smarter cd)
command -v zoxide >/dev/null 2>&1 && eval "$(zoxide init posix --hook prompt)"
# Direnv
command -v direnv >/dev/null 2>&1 && eval "$(direnv hook ksh)"
# History logging (encrypted with SQLCipher)
_kh_db="$HOME/.local/share/history/history.db"
_kh_key_file="$HOME/.local/share/history/.key"
_kh_log() {
typeset cmd="$1" exit_code="$2" pwd_path="$PWD"
[ -z "$cmd" ] && return
case "$cmd" in history*) return ;; esac
[ -f "$_kh_key_file" ] || return
[ -f "$_kh_db" ] || return
typeset escaped_cmd=$(print -r -- "$cmd" | sed "s/'/''/g")
typeset escaped_pwd=$(print -r -- "$pwd_path" | sed "s/'/''/g")
typeset key=$(cat "$_kh_key_file")
(sqlcipher "$_kh_db" "PRAGMA key = '$key'; INSERT INTO terminal_history (command, exit_code, pwd, shell) VALUES ('$escaped_cmd', $exit_code, '$escaped_pwd', 'mksh');" &) >/dev/null 2>&1
}
# PS4 trap to capture commands for history logging
_kh_last_cmd=""
trap '_kh_last_cmd=$(fc -ln -1 2>/dev/null | sed "s/^[[:space:]]*//")' DEBUG
PROMPT_COMMAND='_kh_log "$_kh_last_cmd" "$?"'