#! /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) ===
# The dead check here is 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


update_putty_title() {
    # Skip if terminal is not interactive or xterm/screen-compatible
    [[ "${TERM}" =~ xterm|screen|rxvt ]] || return 0

    # Fallback for legacy bash versions (< 4.4) where ${PS1@P} is unsupported
    if (( "${BASH_VERSINFO}" < 4 )) || \
       [[ "${BASH_VERSINFO}" -eq 4 && "${BASH_VERSINFO}" -lt 4 ]]; then
        if [[ "${TERM}" =~ screen ]]; then
            echo -ne "\033k\u@\h:\w\033\\"
        else
            echo -ne "\033]0;\u@\h:\w\007"
        fi
        return 0
    fi

    local expanded_prompt="${PS1@P}"
    # Remove extra codes
    local clean_title=$(echo -n "${expanded_prompt}" \
      | sed -E 's/\x1B\[[0-9;]*[a-zA-Z]//g' \
      | sed -E 's/\x1B\][0-9;]*[^\x07]*\x07//g' \
      | sed -E 's/\x1B\]133;[^\x1B]*\x1B\\//g')

    # Send title sequence based on terminal type
    if [[ "${TERM}" =~ screen ]]; then
        # GNU Screen internal window title
        echo -ne "\033k${clean_title}\033\\"
    else
        # PuTTY, MATE Terminal, Terminator window title
        echo -ne "\033]0;${clean_title}\007"
    fi
}


### Simple hook into prompt (Review this). It's prone to duplication
### PROMPT_COMMAND="update_history; ${PROMPT_COMMAND}"

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

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

    # rebuild canonical form
    if [[ -n "${pc}" ]]; then
        PROMPT_COMMAND="update_history; update_putty_title; ${pc}"
    else
        PROMPT_COMMAND="update_history; update_putty_title"
    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'



