alias tree='tree -CF --du -h'
alias cbonsai='cbonsai --live --infinite --time 0.3 --base 2 --wait 2 --leaf "&,#,$,*,@"'

alias tmux_main='tmux new-session -s main'
alias tmux_secondary_win='tmux new-session -t main -s secondary'

# enable color support of ls and also add handy aliases
alias ls='ls --color=auto'
alias grep='grep --color=auto'
alias fgrep='grep -F --color=auto'
alias egrep='grep -E --color=auto'

# alias docker=podman

alias d='dirs -v'
for index in 1 2 3 4 5 6 7 8 9; do alias "c$index"="cd +${index}"; done; unset index

alias kpget="keepassxc-cli show -a Password ${KEEPASS_DB}"
alias kptotp="keepassxc-cli show -t ${KEEPASS_DB}"

# --- KeePassXC cached session (password stored in OS keychain) ---
# macOS: security (Keychain)
# Linux: secret-tool (GNOME Keyring via libsecret-tools)
_KP_KEYCHAIN_SVC="keepassxc-cli-cache"
_KP_KEYCHAIN_ACCT="master-password"

_kp_pw_store() {
    case "$UNAME_STRING" in
        Darwin)
            security add-generic-password -U \
                -s "$_KP_KEYCHAIN_SVC" -a "$_KP_KEYCHAIN_ACCT" -w "$1"
            ;;
        Linux)
            echo -n "$1" | secret-tool store --label="$_KP_KEYCHAIN_SVC" \
                service "$_KP_KEYCHAIN_SVC" account "$_KP_KEYCHAIN_ACCT"
            ;;
    esac
}

_kp_pw_get() {
    case "$UNAME_STRING" in
        Darwin)
            security find-generic-password \
                -s "$_KP_KEYCHAIN_SVC" -a "$_KP_KEYCHAIN_ACCT" -w 2>/dev/null
            ;;
        Linux)
            secret-tool lookup \
                service "$_KP_KEYCHAIN_SVC" account "$_KP_KEYCHAIN_ACCT" 2>/dev/null
            ;;
    esac
}

_kp_pw_clear() {
    case "$UNAME_STRING" in
        Darwin)
            security delete-generic-password \
                -s "$_KP_KEYCHAIN_SVC" -a "$_KP_KEYCHAIN_ACCT" &>/dev/null
            ;;
        Linux)
            secret-tool clear \
                service "$_KP_KEYCHAIN_SVC" account "$_KP_KEYCHAIN_ACCT" 2>/dev/null
            ;;
    esac
}

_kp_run() {
    local pw stderr_redir="/dev/null"
    [[ -n "$KP_DEBUG" ]] && stderr_redir="/dev/stderr"
    pw=$(_kp_pw_get)
    if [[ -z "$pw" ]]; then
        read -rs "pw?KeePassXC master password: " </dev/tty && echo
        _kp_pw_store "$pw" || return 1
    fi
    echo "$pw" | keepassxc-cli "$@" 2>"$stderr_redir"
}

kpclose() { _kp_pw_clear && echo "KeePassXC session cleared."; }

# run with KP_DEBUG=1 to troubleshoot if needed
kpgets()  { _kp_run show -sa Password "$KEEPASS_DB" "$1"; }
kptotps() { _kp_run show -st "$KEEPASS_DB" "$1"; }

function totp() {
    local clip=false
    [[ "$1" == "-c" ]] && clip=true && shift

    local code
    case "$1" in
        hcf) code=$(kptotps "personal/Dev/AWS Console") ;;
        aws) code=$(kptotps "work/Own/AWS console") ;;
        pci) code=$(kptotps "work/Own/PCI/AWS Workspaces") ;;
        *)   echo "Usage: totp [-c] {hcf|aws|pci}" >&2; return 1 ;;
    esac

    echo "$code"
    if $clip; then
        case "$UNAME_STRING" in
            Darwin) echo -n "$code" | pbcopy ;;
            Linux) SESSION_ID=$(loginctl session-status | head -n 1 | awk '{print $1}')
                    if loginctl show-session "$SESSION_ID" -p Type | grep -q "Type=wayland"; then
                        echo -n "$code" | wl-copy
                    else
                        echo -n "$code" | xclip -selection clipboard
                    fi ;;

        esac
        echo "(copied to clipboard)"
    fi
}

_get_aws_config_path() {
    local config_path="${AWS_CONFIG_FILE:-$HOME/.aws/config}"
    echo "$config_path"
}

alias awsume="source awsume"

# This label will be set in a comment in the ~/.aws/config file right before
# the definition of the profile we want to use as the default.
# The format will be `#[<label value>]`
# Example, using "admin" as the default profile:
#
# > [default]
# > region = eu-south-2
# >
# > #[<label value>]  ---> Marking the profile with the label
# > [profile admin]
# > source_profile=default
# > region = eu-south-2
# > role_arn=arn:aws:iam::<account id>:role/MyAdminRole
# >
# > [profile readonly]
# > source_profile=default
# > region = eu-south-2
# > role_arn=arn:aws:iam::<account id>:role/MyReadOnlyRole
#
DEFAULT_AWS_PROFILE_LABEL="aws-vault-default"

_get_default_aws_profile() {
    local profile="default"

    if grep -q "^#\[$DEFAULT_AWS_PROFILE_LABEL\]" "$(_get_aws_config_path)"; then
        profile="$(grep -A3 "^#\[$DEFAULT_AWS_PROFILE_LABEL\]" "$(_get_aws_config_path)" |
            grep '^\[profile' |
            sed -E 's/\[profile (.+)\]/\1/')"
    fi

    echo $profile
}

_awsume_cmd() {
    local profile="$(_get_default_aws_profile)"

    if [[ -n "$1" ]]; then
        profile="$1"
    fi

    awsume "$profile"
}

alias asm="_awsume_cmd"

_ensure_awsume() {
    if [[ -z "$AWSUME_PROFILE" ]]; then
        echo "No awsume session found. Starting one..."
        _awsume_cmd || return 1
    fi
}

tf()  { _ensure_awsume && terraform "$@"; }
tfi() { _ensure_awsume && terraform init "$@"; }
tfp() { _ensure_awsume && terraform plan -lock=false "$@"; }
tfa() { _ensure_awsume && terraform apply "$@"; }
tfu() { _ensure_awsume && terraform get -update "$@"; }
tg()  { _ensure_awsume && terragrunt "$@"; }
tgi() { _ensure_awsume && terragrunt init "$@"; }
tgp() { _ensure_awsume && terragrunt plan -lock=false "$@"; }
tga() { _ensure_awsume && terragrunt apply "$@"; }
tgu() { _ensure_awsume && terragrunt get -update "$@"; }

alias curltime="curl -w \"@$HOME/.curl-format.txt\" -o /dev/null -s "

alias vi=nvim
alias vim=nvim

git_root() {
    # Check if we're in a git repository
    if ! git rev-parse --is-inside-work-tree &>/dev/null; then
        echo "Error: Not in a git repository" >&2
        return 1
    fi

    # Get the root of the git repository
    local git_root
    git_root=$(git rev-parse --show-toplevel)

    if [ -n "$git_root" ]; then
        echo "Changing directory to git root: $git_root"
        cd "$git_root"
        return 0
    else
        echo "Error: Could not determine git root directory" >&2
        return 1
    fi
}

alias groot="git_root"

git_push() {
    # Check if we're in a git repository
    if ! git rev-parse --is-inside-work-tree &>/dev/null; then
        echo "Error: Not in a git repository" >&2
        return 1
    fi

    local branch
    branch=$(git branch --show-current)

    git push origin "$branch" "$@"
}

alias gpush="git_push"

passgen() {
    length=${1:-"12"}
    if [[ "$length" == <-> ]]; then
        echo $(cat /dev/urandom| base64 -w0 | head -c "$length")
    else
        echo "passgen() takes a positive integer as first argument"
        echo "got $length"
        return 1
    fi
}
