#!/bin/ksh
# --- Helper Functions ---
traverse_facl() {
    typeset full_path="$1"
    typeset current_path=""
    typeset part
    typeset old_ifs="$IFS"

    IFS="/"
    for part in $full_path; do
        if [ -n "$part" ]; then
            current_path="$current_path/$part"
            setfacl -m m::rwx,u:1000:rwx,u:devuser:rwx,g:devuser:rwx,g:1000:rwx "$current_path"
        fi
    done
    IFS="$old_ifs"
}

# --- System Configuration & Symlinks ---
ln -sPf /var/etc/system/config/sud.cfg /base/etc/system/config/sud.cfg
mkdir -p /var/android/recovery
chmod -R 777 /var/android

# Permissions setup
setfacl -m m::rwx,u:1000:rwx,u:devuser:rwx,g:devuser:rwx,g:1000:rwx /var/android
setfacl -m m::rwx,u:1000:rwx,u:devuser:rwx,g:devuser:rwx,g:1000:rwx /var/android/recovery

traverse_facl "/apps/sys.android.gYABgKAOw1czN6neiAT72SGO.ns/native/system/xbin/btool"
traverse_facl "/apps/sys.android.gYABgKAOw1czN6neiAT72SGO.ns/native/scripts/start-android-core.sh"

RD="/var/rootdata"

# --- Binary Patches & Execution ---
/apps/sys.android.gYABgKAOw1czN6neiAT72SGO.ns/native/system/bin/r
/proc/boot/pathtrust !"${RD}"/launcher_patcher
/proc/boot/pathtrust !/base/bin/mod_nvram

if [ -e "${RD}/use.root" ]; then
    /proc/boot/pathtrust !/base/bin/__root
    /proc/boot/pathtrust !/base/bin/u_root
fi

"${RD}/launcher_patcher" >> /tmp/launcher_patcher.log 2>&1

# --- Network & Services ---
slay -f sshd 2>/dev/null
if [ -e "${RD}/use.sshd" ]; then
    print -r -- "usbdnet_ipaddr::169.254.0.1" >> /pps/services/usbd/settings
    /usr/sbin/sshd
fi

# --- Root Notifications ---
TS_ROOT=$(date -t 2>/dev/null || date +%s)
print -r -- "msg::Notify
dat:json:{\"Title\":\"root\",\"Subtitle\":\"Congratulations! The device has been successfully rooted!\",\"Type\":\"alertuib\",\"AppId\":\"sys.service\",\"ItemId\":\"root${TS_ROOT}\",\"PayloadURI\":\"https://bb10.root.sx/\"}" >> /pps/system/notify/control

print -r -- "msg::wakeupDevice
dat::" >> /pps/system/navigator/control

# --- NVRAM Backup Management ---
BASE="/accounts/1000/shared/downloads/nvram"
DIR="$BASE/$(date +'%Y%m%d-%H%M%S')"

if mod_nvram -b "$DIR" && chown -R 1000:1000 "$DIR" && chmod -R 755 "$BASE" && ln -sPf "$DIR" "$BASE/latest"; then
    set -- "$BASE"/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-*

    if [ -e "$1" ] && [ -d "$1" ]; then
        total=$#

        if [ $total -gt 4 ]; then
            set -A backups -- "$@"

            max_idx=$((total - 4))
            i=1

            while [ $i -le $max_idx ]; do
                dir_to_remove="${backups[$i]}"
                if [ -n "$dir_to_remove" ] && [ -d "$dir_to_remove" ]; then
                    echo "Removing old backup: $dir_to_remove"
                    rm -rf "$dir_to_remove"
                fi
                i=$((i + 1))
            done
        fi
    fi
fi

# --- Stop Background Services ---
/base/scripts/startup.sh sanitymonitor stop
/base/scripts/startup.sh bbidd stop
/base/scripts/startup.sh racd stop
/base/scripts/startup.sh analyticd stop
/base/scripts/startup.sh bbauthengine stop
/base/scripts/startup.sh ebm stop
/base/scripts/startup.sh ema stop
/base/scripts/startup.sh quip stop
/base/scripts/startup.sh mplog stop

# --- Package Installation ---
if [ -f /base/scripts/sudtools.sh ]; then
    . /base/scripts/sudtools.sh
fi

if [ ! -e "${RD}/term49.installed" ]; then
    touch "${RD}/term49.installed"
    sud_install_package "${RD}/Term49.bar"
fi

# Kill existing sud.py
pid=$(pidin -F "%a %A" 2>/dev/null | awk '/[p]ython/ && /sud\.py/ {print $1}')
[ -n "$pid" ] && slay -fQ -sTERM "$pid"