# rc file is stored as read only:
/system/etc/mkshrc

# create Magisk module 
mkdir -p /data/adb/modules/mybin/system/etc/
cp /system/etc/mkshrc /data/adb/modules/mybin/system/etc/
busybox vi /data/adb/modules/mybin/system/etc/mkshrc 

# reboot is normally required for new files to be scene
# but if you make changes and want to update the system
# without rebooting you can remount the file
mount --bind /data/adb/modules/mybin/system/etc/mkshrc /system/etc/mkshrc

#### EXAMPLE mkshrc ####
## Define ANSI color constants for MKSH
#if [ -z "$BUSYBOX_ACTIVE" ]; then
    export BUSYBOX_ACTIVE=1
    export ENV=/system/etc/mkshrc
    exec /system/bin/busybox sh
fi

# Define history target path
export HISTFILE="/sdcard/ash_history"
export HISTSIZE=1000
export SAVEHIST=1000

# Force create the target history file right now if it does not exist
if [ ! -f "$HISTFILE" ]; then
    touch "$HISTFILE" 2>/dev/null
    chmod 666 "$HISTFILE" 2>/dev/null
fi

# Dynamically generate a literal Escape character (\033) into a variable
# This bypasses BusyBox's root string expansion restrictions
ESC=$(printf '\033')

# Assign raw escape colors
CLR_RED="${ESC}[1;31m"
CLR_GREEN="${ESC}[1;32m"
CLR_YELLOW="${ESC}[1;33m"
CLR_CYAN="${ESC}[1;36m"
CLR_RESET="${ESC}[0m"

# Auto-Save Engine: This function takes live line data and forces it to disk
save_history_instant() {
    local LAST_CMD=$(history | tail -n1 | awk '{$1=""; print $0}' 2>/dev/null | sed 's/^[ \t]*//')
    if [ -n "$LAST_CMD" ]; then
        # Append line to file, checking to make sure it isn't an exact duplicate of the last entry
        if [ "$LAST_CMD" != "$(tail -n 1 "$HISTFILE" 2>/dev/null)" ]; then
            echo "$LAST_CMD" >> "$HISTFILE"
        fi
    fi
}

# Dynamically build prompts that trigger 'save_history_instant' on every line generation
if [ "$(id -u)" = "0" ] || [ "$USER" = "root" ]; then
    # Root Prompt (Red)
    export PS1='$(save_history_instant)['${CLR_RED}'$USER'${CLR_RESET}'@'${CLR_CYAN}'$HOSTNAME'${CLR_RESET}': '${CLR_YELLOW}'${PWD}'${CLR_RESET}'] # '
else
    # Shell User Prompt (Green)
    export PS1='$(save_history_instant)['${CLR_GREEN}'$USER'${CLR_RESET}'@'${CLR_CYAN}'$HOSTNAME'${CLR_RESET}': '${CLR_YELLOW}'${PWD}'${CLR_RESET}'] $ '
fi

# Base Aliases
alias ll="ls -lha"
alias vi="busybox vi"
alias vim="busybox vi"
alias wget="busybox wget"
alias volname="busybox volname"
alias w="busybox w"
alias wall="busybox wall"
alias which="busybox which"
alias who="busybox who"
alias whoami="busybox whoami"
alias whois="busybox whois"
alias ssu="su -c \"/system/bin/busybox sh\""
alias ff="find 2>/dev/null| fzf"
alias x="exit"

update_rc(){
        local rc_file="/data/adb/modules/mybin/system/etc/mkshrc"
        su -c "busybox vi $rc_file"
        echo "To apply changes run:"
        echo "su -c \"mount --bind $rc_file /system/etc/mkshrc\""
}

alias zrc="update_rc"
