#!/bin/bash
#
# Program: update-tlbweb-latest (Copyright) Jul 25, 2026
# Authors: Paul Aidukas - KN2R, Logan Crook - K8LRC
#
# Get/install latest Official LinkBox web update
# from the package host — same idea as supermonASL_latest_update.
#
# 25-Jul-2026  Paul-KN2R / Logan-K8LRC  Initial release (Paul-style wrapper).
# 26-Jul-2026  Logan-K8LRC              Match Paul ASL latest_update layout.
# 05-Aug-2026  Logan-K8LRC              Do not leave TheLinkBox down after update
#                                       (tmp extract, strip restart-tlb exec bits,
#                                        verify tlb after apache reload).
#
###############################################################

OSR=`cat /etc/os-release | egrep -i '^id=' |  awk -F '=' '{print $2}' | tr -d '"'`
if [ "$OSR" != "debian" ] && [ "$OSR" != "raspbian" ]; then
    echo -e "\nThis is NOT a DEBIAN / Raspbian system!"
    echo "You must get and run the correct installer for your system image."
    echo -e "Update aborted.\n\a"
    exit 1
fi

if [ "`id -u`" -ne 0 ]; then
    echo -e "\nRun as root:\n  sudo $0\n\a"
    exit 1
fi

echo -e "\nStarting update...\n"

# Safe PATH — never include "." or the extract dir (package ships restart-tlb*).
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Package host (IP first — some networks block crabdance.com DDNS)
# Override:  PKG_URL='http://linkbox.k8lrc.crabdance.com' sudo ./update-tlbweb-latest
PKG_URL="${PKG_URL:-http://45.32.193.131}"
PACKAGE_URL="${PACKAGE_URL:-${PKG_URL%/}/tlb-2+}"
export PACKAGE_URL PKG_URL

tlb_is_up() {
    pidof tlb >/dev/null 2>&1 && return 0
    pgrep -x tlb >/dev/null 2>&1 && return 0
    pgrep -f '/usr/local/libexec/tlb( |$)' >/dev/null 2>&1 && return 0
    pgrep -f '/usr/local/sbin/tlb( |$)' >/dev/null 2>&1 && return 0
    pgrep -f '/usr/sbin/tlb( |$)' >/dev/null 2>&1 && return 0
    return 1
}

start_tlb_safe() {
    echo "update-tlbweb-latest: Starting TheLinkBox (tlb)..."
    if command -v systemctl >/dev/null 2>&1; then
        systemctl start tlb >/dev/null 2>&1 || true
        sleep 1
        if tlb_is_up; then
            echo "update-tlbweb-latest: tlb started via systemctl"
            return 0
        fi
    fi
    conf="/home/thelinkbox/tlb.conf"
    for bin in /usr/local/libexec/tlb /usr/local/sbin/tlb /usr/sbin/tlb /usr/bin/tlb; do
        if [ -x "$bin" ] && [ -f "$conf" ]; then
            ( cd /home/thelinkbox && "$bin" -d -f "$conf" >/dev/null 2>&1 & ) || true
            sleep 1
            if tlb_is_up; then
                echo "update-tlbweb-latest: tlb started via $bin"
                return 0
            fi
        fi
    done
    # Last resort: operator restart script (may systemctl stop then start).
    for rs in \
        /home/thelinkbox/scripts/restart-tlb \
        /home/thelinkbox/scripts/restart-tlb-nopolicy \
        /home/thelinkbox/scripts/restart-tlb-conference
    do
        if [ -x "$rs" ]; then
            echo "update-tlbweb-latest: trying $rs"
            "$rs" || true
            sleep 1
            if tlb_is_up; then
                echo "update-tlbweb-latest: tlb started via $rs"
                return 0
            fi
        fi
    done
    echo "update-tlbweb-latest: ERROR — could not start tlb; start it manually" >&2
    return 1
}

ensure_tlb_up() {
    reason="$1"
    if tlb_is_up; then
        echo "update-tlbweb-latest: TheLinkBox (tlb) is running ($reason)"
        return 0
    fi
    echo "update-tlbweb-latest: WARNING — tlb is NOT running ($reason)"
    start_tlb_safe || true
}

TLB_WAS_UP=0
if tlb_is_up; then
    TLB_WAS_UP=1
    echo "update-tlbweb-latest: tlb is running before update"
else
    echo "update-tlbweb-latest: tlb is not running before update"
fi

# Extract under /tmp — never leave executable restart-tlb* at /tlb-2+ on /.
WORKDIR="/tmp/tlb-2+-update.$$"
rm -rf "$WORKDIR"
mkdir -p "$WORKDIR"
cd "$WORKDIR" || exit 1

wget "${PKG_URL%/}/tlb-2+-web.tgz" -O tlb-2+-web.tgz
sync
tar -xzf tlb-2+-web.tgz
sync
rm -f tlb-2+-web.tgz

if [ ! -d "$WORKDIR/tlb-2+" ]; then
    echo -e "\nERROR: tgz did not contain tlb-2+/ directory\n\a"
    rm -rf "$WORKDIR"
    exit 1
fi

cd "$WORKDIR/tlb-2+" || exit 1
chmod +x install-tlbweb.sh update-tlbweb.sh

# Package samples include restart-tlb* (they killall tlb). Never executable here.
chmod a-x restart-tlb restart-tlb.sample \
    restart-tlb-nopolicy restart-tlb-nopolicy.sample \
    restart-tlb-conference restart-tlb-conference.sample 2>/dev/null || true

# Web update only — must not stop TheLinkBox.
./update-tlbweb.sh "$@"
UPDATE_RC=$?

ensure_tlb_up "after update-tlbweb.sh"

# Remove legacy web-root LinkBox public monitor if present (never touch tlb-admin/)
if [ -f /var/www/html/index.php ]; then
    if grep -qE 'exp_render_live_panel|tlb-common\.inc|LinkBox Monitor|tlbcmdport' /var/www/html/index.php 2>/dev/null; then
        stamp=`date +%Y%m%d%H%M%S`
        cp -a /var/www/html/index.php /var/www/html/index.php.bak.$stamp
        rm -f /var/www/html/index.php
        echo "Removed legacy public monitor /var/www/html/index.php (backup: index.php.bak.$stamp)"
    fi
fi

# Prefer reload — full apache restart is unnecessary for PHP file updates and
# has been associated with tlb going down on some operator boxes.
if systemctl reload apache2 >/dev/null 2>&1; then
    echo "update-tlbweb-latest: apache2 reloaded"
else
    service apache2 force-reload >/dev/null 2>&1 || systemctl restart apache2 >/dev/null 2>&1 || true
    echo "update-tlbweb-latest: apache2 reload/restart attempted"
fi

ensure_tlb_up "after apache"

# If tlb was up at the start, insist it is up at the end.
if [ "$TLB_WAS_UP" -eq 1 ] && ! tlb_is_up; then
    echo "update-tlbweb-latest: tlb was up before update — forcing another start attempt"
    start_tlb_safe || true
fi

rm -rf "$WORKDIR"
sync

if tlb_is_up; then
    echo -e "\nAll tasks completed. TheLinkBox (tlb) is running.\n"
else
    if [ "$TLB_WAS_UP" -eq 1 ]; then
        echo -e "\nAll tasks completed, but tlb is DOWN — start it manually:\n  systemctl start tlb\n  OR: /home/thelinkbox/scripts/restart-tlb\n\a"
    else
        echo -e "\nAll tasks completed. (tlb was not running before update)\n"
    fi
fi

exit $UPDATE_RC

# The end ;)
###############################################################
