#!/bin/bash

# Check for interactive shell
iatest=$(expr index "$-" i)

# Display Fastfetch if available
[ -f /usr/bin/fastfetch ] && fastfetch -c ~/.config/fastfetch/config-compact.jsonc

# Source system-wide bashrc and completion files if they exist
for file in /etc/bashrc /usr/share/bash-completion/bash-completion /etc/bash_completion; do
    [ -f "$file" ] && . "$file"
done

# Configure bell style for interactive shells
[[ $iatest -gt 0 ]] && bind "set bell-style visible"

# History settings
export HISTFILESIZE=10000
export HISTSIZE=500
export HISTCONTROL=erasedups:ignoredups:ignorespace

# Set vi mode for command line
set -o vi
bind 'set show-mode-in-prompt on'
set vi-ins-mode-string \1\e[6 q\2
set vi-cmd-mode-string \1\e[2 q\2

# Shell options
shopt -s checkwinsize histappend
PROMPT_COMMAND='history -a'

# Terminal settings
[[ $- == *i* ]] && stty -ixon

# Auto-completion settings
[[ $iatest -gt 0 ]] && {
    bind "set completion-ignore-case on"
    bind "set show-all-if-ambiguous on"
}

# Default editor
export EDITOR=nvim
export VISUAL=nvim
alias pico='edit'
alias spico='sedit'
alias nano='edit'
alias snano='sedit'
alias vim='nvim'
alias cat='bat'

# Enable colors for various commands
export CLICOLOR=1
export LS_COLORS='no=00:fi=00:di=00;34:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.ogg=01;35:*.mp3=01;35:*.wav=01;35:*.xml=00;31:'
alias grep="/usr/bin/grep --color=auto"

# Configure man page colors
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'

#######################################################
# GENERAL ALIASES
#######################################################
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history | tail -n1 | sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'' )"'
alias ebrc='edit ~/.bashrc'
alias hlp='less ~/.bashrc_help'
alias da='date "+%Y-%m-%d %A %T %Z"'
alias cp='cp -i'
alias mv='mv -i'
alias rm='trash -v'
alias mkdir='mkdir -p'
alias ps='ps auxf'
alias ping='ping -c 10'
alias less='less -R'
alias cls='clear'
alias apt-get='sudo apt-get'
alias multitail='multitail --no-repeat -c'
alias freshclam='sudo freshclam'
alias vi='nvim'
alias svi='sudo vi'
alias vis='nvim "+set si"'
alias home='cd ~'
alias cd..='cd ..'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'
alias bd='cd "$OLDPWD"'
alias rmd='/bin/rm --recursive --force --verbose '
alias la='ls -Alh'
alias ls='ls -aFh --color=always'
alias lx='ls -lXBh'
alias lk='ls -lSrh'
alias lc='ls -lcrh'
alias lu='ls -lurh'
alias lr='ls -lRh'
alias lt='ls -ltrh'
alias lm='ls -alh | more'
alias lw='ls -xAh'
alias ll='ls -Fls'
alias labc='ls -lap'
alias lf="ls -l | grep -E -v '^d'"
alias ldir="ls -l | grep -E '^d'"

# File permission aliases
alias mx='chmod a+x'
alias 000='chmod -R 000'
alias 644='chmod -R 644'
alias 666='chmod -R 666'
alias 755='chmod -R 755'
alias 777='chmod -R 777'

# History search
alias hs="history | fzf "
alias p="ps aux | grep "
alias topcpu="/bin/ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10"
alias f="find . | grep "
alias countfiles="for t in files links directories; do echo \`find . -type \${t:0:1} | wc -l\` \$t; done 2> /dev/null"
alias checkcommand="type -t"
alias openports='netstat -nape --inet'
alias rebootsafe='sudo shutdown -r now'
alias rebootforce='sudo shutdown -r -n now'
alias diskspace="du -S | sort -n -r | more"
alias folders='du -h --max-depth=1'
alias folderssort='find . -maxdepth 1 -type d -print0 | xargs -0 du -sk | sort -rn'
alias tree='tree -CAhF --dirsfirst'
alias treed='tree -CAFd'
alias mountedinfo='df -hT'
alias mktar='tar -cvf'
alias mkbz2='tar -cvjf'
alias mkgz='tar -cvzf'
alias untar='tar -xvf'
alias unbz2='tar -xvjf'
alias ungz='tar -xvzf'
alias logs="sudo find /var/log -type f -exec file {} \; | grep 'text' | cut -d' ' -f1 | sed -e's/:$//g' | grep -v '[0-9]$' | xargs tail -f"
alias sha1='openssl sha1'
alias clickpaste='sleep 3; xdotool type "$(xclip -o -selection clipboard)"'

#######################################################
# SPECIAL FUNCTIONS
#######################################################

extract() {
    for archive in "$@"; do
        if [ -f "$archive" ]; then
            case $archive in
                *.tar.bz2) tar xvjf "$archive" ;;
                *.tar.gz) tar xvzf "$archive" ;;
                *.bz2) bunzip2 "$archive" ;;
                *.rar) rar x "$archive" ;;
                *.gz) gunzip "$archive" ;;
                *.tar) tar xvf "$archive" ;;
                *.tbz2) tar xvjf "$archive" ;;
                *.tgz) tar xvzf "$archive" ;;
                *.zip) unzip "$archive" ;;
                *.Z) uncompress "$archive" ;;
                *.7z) 7z x "$archive" ;;
                *) echo "don't know how to extract '$archive'..." ;;
            esac
        else
            echo "'$archive' is not a valid file!"
        fi
    done
}

ftext() {
    grep -iIHrn --color=always "$1" . | less -r
}

cpp() {
    set -e
    total_size="$(stat -c '%s' "$1")"
    strace -q -ewrite cp -- "$1" "$2" 2>&1 |
        awk -v total_size="$total_size" '{
            count += $NF
            if (count % 10 == 0) {
                percent = count / total_size * 100
                printf "%3d%% [", percent
                for (i=0; i <= percent; i++) printf "="
                printf ">"
                for (i=percent; i < 100; i++) printf " "
                printf "]\r"
            }
        }
        END { print "" }'
}

cpg() {
    cp "$1" "$2" && [ -d "$2" ] && cd "$2"
}

mvg() {
    mv "$1" "$2" && [ -d "$2" ] && cd "$2"
}

mkdirg() {
    mkdir -p "$1" && cd "$1"
}

up() {
    local d=""
    local limit=$1
    for ((i = 1; i <= limit; i++)); do
        d="$d/.."
    done
    d=${d#/}  # Remove leading slash
    cd "${d:-..}"
}

cd() {
    builtin cd "$@" && ls
}

pwdtail() {
    pwd | awk -F/ '{nlast = NF -1; print $nlast"/"$NF}'
}

distribution() {
    local dtype="unknown"
    [ -r /etc/os-release ] && {
        source /etc/os-release
        case $ID in
            fedora|rhel|centos) dtype="redhat" ;;
            sles|opensuse*) dtype="suse" ;;
            ubuntu|debian) dtype="debian" ;;
            gentoo) dtype="gentoo" ;;
            arch) dtype="arch" ;;
            slackware) dtype="slackware" ;;
        esac
    }
    echo "$dtype"
}

ver() {
    local dtype=$(distribution)
    case $dtype in
        redhat) [ -s /etc/redhat-release ] && cat /etc/redhat-release || cat /etc/issue ;;
        suse) cat /etc/SuSE-release ;;
        debian) lsb_release -a ;;
        gentoo) cat /etc/gentoo-release ;;
        arch) cat /etc/os-release ;;
        slackware) cat /etc/slackware-version ;;
        *) [ -s /etc/issue ] && cat /etc/issue || echo "Error: Unknown distribution" ;;
    esac
}

whatismyip() {
    echo -n "Internal IP: "
    if command -v ip &>/dev/null; then
        /sbin/ip addr show wlan0 | awk '/inet /{print $2}' | cut -d/ -f1
    else
        /sbin/ifconfig wlan0 | awk '/inet /{print $2}'
    fi
    echo -n "External IP: "
    curl -s ifconfig.me
}

trim() {
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"  # remove leading whitespace
    var="${var%"${var##*[![:space:]]}"}"  # remove trailing whitespace
    echo -n "$var"
}

# OS-specific aliases for Arch
if [[ "$(distribution)" == "arch" ]]; then
    alias \
        pacfiles='pacman -F' \
        pacfileupg='sudo pacman -Fy' \
        pacin='sudo pacman -S' \
        pacins='sudo pacman -U' \
        pacinsd='sudo pacman -S --asdeps' \
        paclean='sudo pacman -Sc' \
        pacloc='pacman -Qi' \
        paclocs='pacman -Qs' \
        paclr='sudo pacman -Scc' \
        pacls='pacman -Ql' \
        paclsorphans='sudo pacman -Qdt' \
        pacmanallkeys='sudo pacman-key --refresh-keys' \
        pacmir='sudo pacman -Syy' \
        pacown='pacman -Qo' \
        pacre='sudo pacman -R' \
        pacrem='sudo pacman -Rns' \
        pacrep='pacman -Si' \
        pacreps='pacman -Ss' \
        pacrmorphans='sudo pacman -Rs $(pacman -Qtdq)' \
        pacupd='sudo pacman -Sy' \
        pacupg='sudo pacman -Syu'
fi

# GitHub shortcuts
gcom() {
    git add . && git commit -m "$1"
}

lazyg() {
    git add . && git commit -m "$1" && git push
}

# PATH modifications
export PATH="$PATH:$HOME/.local/bin:/var/lib/flatpak/exports/bin:$HOME/.local/share/flatpak/exports/bin:$HOME/.npm/bin"

# Initialize Starship, Zoxide, and other tools
eval "$(starship init bash)"
eval "$(zoxide init bash)"
