#! /bin/bash
# /etc/profile.d/Custom_Bash.sh

# Safe, deduplicated, periodic, bash history merge for login shells

# Abort if not in a login shell
#[[ $0 == -* ]] || return

# Run only in interactive shells
# The i flag is the most dependable marker of an interactive shell
[[ $- == *i* ]] || return

# === Shell options and history settings ===
shopt -s autocd
shopt -s histappend                    # Append to history file, don't overwrite

export HISTSIZE=32768                  # RAM history size
export HISTFILESIZE=65536              # Max history file size
export HISTIGNORE="history*:exit"      # Ignore certain commands
export NO_AT_BRIDGE=1                  # Reduce GTK/AT warnings
export NCURSES_NO_UTF8_ACS=1           # UTF8-friendly ncurses
export HISTCONTROL=ignoredups:erasedups:ignorespace
export HISTFILE="${HOME}/.bash_history"

# Ensure history file exists
touch "$HISTFILE"

# === Deduplicate on-disk history (login shells only) ===
# dead check kept, intentionally, as a refactoring guard
if shopt -q login_shell ; then

    # Open read/write without truncation
    exec {history_fd}<>"${HISTFILE}" || {
        echo "Failed open during deduplication" >&2; return;
    }

    # Lock exclusively
    flock -x -w 5 "${history_fd}" || {
        echo "Failed Lock during deduplication" >&2; return;
    }

    # Safe temporary file
    tmpfile=$(mktemp "${HISTFILE}.tmp.XXXXXXXXXX") || {
        echo "Failed mktemp during deduplication" >&2; return;
    }

    # Order preserving deduplication (tac -> perl -> tac)
    # awk '!seen[$0]++' is cleaner, but perl is faster
    tac < "${HISTFILE}" \
      | perl -ne '$Seen{$_}++ or print' \
      | tac > "${tmpfile}"

    # Atomic replace
    mv -f -- "${tmpfile}" "${HISTFILE}"

    flock -u "${history_fd}"
    unset history_fd
fi


# === History update utilities ===

LAST_UPDATE=${SECONDS}

update_history() {

    if (( SECONDS - LAST_UPDATE > 60 )); then

        exec {history_fd}<>"${HISTFILE}" || {
            echo "Failed open during update" >&2; return;
        }
        flock -x -w 5 "${history_fd}" || {
            echo "Failed Lock during update" >&2; return;
        }

        # history -n    # intentionally omitted - read new entries from disk
        history -a      # append our new entries

        flock -u "${history_fd}"
        unset history_fd

        LAST_UPDATE=${SECONDS}

        # ---------------- BEGIN COLLAPSE ------------------#
        # FIXME: collapse branches once continuous updates
        # are no longer needed.
    else
        exec {history_fd}<>"${HISTFILE}" || {
            echo "Failed open during update" >&2; return;
        }
        flock -x -w 5 "${history_fd}" || {
            echo "Failed Lock during update" >&2; return;
        }
        # history -n    # intentionally omitted - read new entries from disk

        history -a      # append our new entries
                        # history -c && history -r   # to reload from disk

        flock -u "${history_fd}"
        unset history_fd
        # ----------------- END COLLAPSE -------------------#
    fi
}

force_update_on_exit() {
    exec {history_fd}<>"${HISTFILE}" || {
        echo "Failed open during exit" >&2; return;
    }
    flock -x -w 5 "${history_fd}" || {
        echo "Failed Lock during exit" >&2; return;
    }

    history -a      # the final flush

    flock -u "${history_fd}"
    unset history_fd
}

# Trap exit to ensure history is flushed
# Dead check "are we in a login shell" kept intentionally, as a refactoring guard
shopt -q login_shell && trap force_update_on_exit EXIT


### Hook into prompt Review this. it's symplistic and prone to dupèlication
### PROMPT_COMMAND="update_history; ${PROMPT_COMMAND}"

# Hook into prompt (idempotent insertion)
__rebuild_prompt_command() {
    local pc="$PROMPT_COMMAND"

    # remove any existing update_history occurrences
    pc=$(printf '%s' "$pc" | sed -E 's/(^|;[[:space:]]*)update_history([[:space:]]*;|$)//g')

    # rebuild canonical form
    if [[ -n $pc ]]; then
        PROMPT_COMMAND="update_history; $pc"
    else
        PROMPT_COMMAND="update_history"
    fi
}

__rebuild_prompt_command




# === Useful defaults ===

export EDITOR="/usr/bin/ne"
export VISUAL="/usr/bin/ne"

alias eatmydata='LD_PRELOAD=/opt/libeatmydata/libeatmydata.so'
alias df='df -h | grep -v /run/.*/systemd-.*\\.service$ | { sed -u 1q; sort -k1; }'
alias du="du -sh"
alias s="sudo su -"
alias pkill="pkill -e"
alias gedit="pluma"
alias ipa="ip -br -c a"
alias sc="systemctl"
alias jc="journalctl"
alias fd='fdisk -l | grep "Disk\s/dev/"'
alias ytmp3='youtube-dl --extract-audio --audio-format mp3'
alias ls='ls --color=auto --classify --escape --group-directories-first'


