#!/bin/bash

BOGEN_DIR=/opt/bogen
INCOMING_DIR=$BOGEN_DIR/incoming


BOGEN_LOG_DIR=$BOGEN_DIR/logs
BOGEN_APP_DIR=$BOGEN_DIR/appliance
BOGEN_ARCHIVE_DIR=$BOGEN_DIR/archive
BOGEN_FACT_DEF_DIR=$BOGEN_DIR/default
BOGEN_BIN_DIR=/usr/sbin
BOGEN_APP_NAME=nyq-appliance
NYQ_VAR_OPT_DIR=/var/opt/nyquist
BACKUPS_DIR=$NYQ_VAR_OPT_DIR/backups
USR_BIN_DIR=/usr/local/bin
USR_LOCAL_SBIN_DIR=/usr/local/sbin
THIRD_PARTY_DIR=ext/third_party

USR_LIB_DIR=usr/lib
USR_LOCAL_LIB_DIR=usr/local/lib
USR_ARM_LIB=/usr/lib/arm-linux-gnueabihf/

USR_INCLUDE_DIR=/usr/include

WEB_UI_DIR=var/www
LIGHTTPD_CONF_DIR=/etc/lighttpd/conf-available
PHP_DIR=etc/php5

NYQ_CFG_DIR=/etc/nyquist
NYQ_BACKUP_DIR=/tmp/nyq_backup

UPDATE_STATE_DIR=$NYQ_VAR_OPT_DIR/update-state
UPDATE_FLAG=$UPDATE_STATE_DIR/update-in-progress

log()  { printf '%s\n' "$*" >&2; }
warn() { log "WARNING: $*"; }
err()  { log "ERROR:   $*"; }

# Firmware helpers (log loudly to stderr and also to UPDATE_LOG when available)
fw_log()  { log "[FW] $*"; sudo bash -c "echo [FW] $* >> '$UPDATE_LOG'" 2>/dev/null || true; }
fw_warn() { warn "[FW] $*"; sudo bash -c "echo WARNING: [FW] $* >> '$UPDATE_LOG'" 2>/dev/null || true; }
fw_err()  { err "[FW] $*"; sudo bash -c "echo ERROR: [FW] $* >> '$UPDATE_LOG'" 2>/dev/null || true; }

# Copy ANY .hex firmware found under one-or-more search roots into /lib/firmware.
# Best-effort: continue on errors, but log loudly. Also retries find() to avoid transient "no results".
copy_hex_firmware_best_effort() {
  local dest_dir="/lib/firmware"
  local max_retries=5
  local retry_delay=1

  # Build a list of existing roots only (missing roots are common during updates)
  local -a roots=()
  local d
  for d in "$@"; do
    [ -n "$d" ] && [ -d "$d" ] && roots+=("$d")
  done

  if (( ${#roots[@]} == 0 )); then
    fw_err "no firmware search directories exist; nothing to copy"
    return 0
  fi

  # Ensure destination exists
  if ! sudo mkdir -p "$dest_dir"; then
    fw_err "failed to create $dest_dir; skipping firmware copy"
    return 0
  fi

  local attempt=1
  local -a found=()
  local f

  # Small flush to reduce "find sees nothing" right after extraction/mount activity
  sync >/dev/null 2>&1 || true

  while (( attempt <= max_retries )); do
    found=()
    while IFS= read -r -d '' f; do
      found+=("$f")
    done < <(find "${roots[@]}" -type f -name "*.hex" -print0 2>/dev/null)

    if (( ${#found[@]} > 0 )); then
      break
    fi

    fw_warn "no .hex firmware found (attempt $attempt/$max_retries); retrying in ${retry_delay}s..."
    sleep "$retry_delay"
    ((attempt++))
  done

  if (( ${#found[@]} == 0 )); then
    fw_err "no .hex firmware found after $max_retries attempts (roots: ${roots[*]})"
    return 0
  fi

  fw_log "found ${#found[@]} .hex file(s); copying to $dest_dir"

  local src fname dest tmp
  for src in "${found[@]}"; do
    fname="$(basename "$src")"
    dest="$dest_dir/$fname"
    tmp="$dest.tmp.$$"

    fw_log "installing $fname from $src"

    if ! sudo install -o root -g root -m 0644 "$src" "$tmp"; then
      fw_err "install failed for $src"
      sudo rm -f "$tmp" >/dev/null 2>&1 || true
      continue
    fi

    if ! sudo mv -f "$tmp" "$dest"; then
      fw_err "atomic move failed for $dest"
      sudo rm -f "$tmp" >/dev/null 2>&1 || true
      continue
    fi

    # Optional verification when available
    if command -v sha256sum >/dev/null 2>&1; then
      local srcsum dstsum
      srcsum="$(sha256sum "$src" | awk '{print $1}')" || srcsum=""
      dstsum="$(sudo sha256sum "$dest" | awk '{print $1}')" || dstsum=""
      if [[ -n "$srcsum" && -n "$dstsum" && "$srcsum" != "$dstsum" ]]; then
        fw_err "checksum mismatch for $fname ($src -> $dest)"
      fi
    fi
  done
}

copy_fw_one_best_effort() {
  local src_root="$1"   # e.g. "$BOGEN_DIR/components/common/images"
  local filename="$2"   # e.g. "E7020.hex"
  local dest="/lib/firmware/$filename"

  # Find matches safely (null-delimited)
  local -a matches=()
  while IFS= read -r -d '' f; do
    matches+=("$f")
  done < <(find "$src_root" -type f -name "$filename" -print0 2>/dev/null)

  if (( ${#matches[@]} == 0 )); then
    warn "firmware '$filename' not found under '$src_root' (skipping install)"
    return 0
  fi

  if (( ${#matches[@]} > 1 )); then
    err "multiple matches for '$filename' under '$src_root' (skipping install to avoid wrong file):"
    printf '  %s\n' "${matches[@]}" >&2
    return 0
  fi

  local src="${matches[0]}"

  # Ensure destination dir exists
  if ! sudo mkdir -p /lib/firmware; then
    err "failed to create /lib/firmware (skipping '$filename')"
    return 0
  fi

  # Copy to temp, then atomic replace
  local tmp="${dest}.tmp.$$"
  if ! sudo install -o root -g root -m 0644 "$src" "$tmp"; then
    err "install failed for '$filename' from '$src' -> '$tmp' (skipping)"
    sudo rm -f "$tmp" >/dev/null 2>&1 || true
    return 0
  fi

  if ! sudo mv -f "$tmp" "$dest"; then
    err "atomic move failed for '$filename' ($tmp -> $dest) (skipping)"
    sudo rm -f "$tmp" >/dev/null 2>&1 || true
    return 0
  fi

  # Verify content matches (if sha256sum exists)
  if command -v sha256sum >/dev/null 2>&1; then
    local srcsum dstsum
    srcsum="$(sha256sum "$src" | awk '{print $1}')" || srcsum=""
    dstsum="$(sudo sha256sum "$dest" | awk '{print $1}')" || dstsum=""
    if [[ -z "$srcsum" || -z "$dstsum" ]]; then
      warn "checksum unavailable for '$filename' (installed, but verification failed to run)"
    elif [[ "$srcsum" != "$dstsum" ]]; then
      err "checksum mismatch for '$filename' (installed file may be wrong/corrupt): $src -> $dest"
    else
      log "Installed $filename from $src -> $dest (sha256 $dstsum)"
    fi
  else
    log "Installed $filename from $src -> $dest (sha256sum not available; not verified)"
  fi

  return 0
}

disable_rsyslog_xconsole_action() {
    fw_log "Disabling rsyslog xconsole action to stop action 20-23 suspended noise..."

    sudo cp -p /etc/rsyslog.conf /etc/rsyslog.conf.bak

    sudo perl -0pi -e 's@(?m)^daemon\.\*;mail\.\*;\\\n\s*news\.err;\\\n\s*\*\.=debug;\*\.=info;\\\n\s*\*\.=notice;\*\.=warn\s+\|/dev/xconsole@#daemon.*;mail.*;\\\n#    news.err;\\\n#    *.=debug;*.=info;\\\n#    *.=notice;*.=warn    |/dev/xconsole@' /etc/rsyslog.conf

    sudo rsyslogd -N1 >/tmp/rsyslog-check.txt 2>&1
    if [ $? -ne 0 ]; then
        fw_err "rsyslog config validation failed after disabling xconsole"
        sudo cat /tmp/rsyslog-check.txt >&2
        sudo cp -pf /etc/rsyslog.conf.bak /etc/rsyslog.conf
        return 1
    fi

    sudo rm -f /etc/rsyslog.d/00-silence-rsyslog-action-retries.conf
    sudo service rsyslog restart
    fw_log "Disabled rsyslog xconsole action."
}
NYQUIST_VER_FILE=$BOGEN_APP_DIR/VERSION.config
#Create directory for logs (if it doesn't exist)
if [ ! -d "$BOGEN_LOG_DIR" ]; then
        sudo mkdir ${BOGEN_LOG_DIR}
fi
if [ ! -d "$BOGEN_APP_DIR" ]; then
        sudo mkdir ${BOGEN_APP_DIR}
fi

UPDATE_LOG=$BOGEN_LOG_DIR/Update-log-`date +%F-%R`.txt
sudo touch $UPDATE_LOG
sudo chown root:www-data $UPDATE_LOG
sudo bash -c "date >> $UPDATE_LOG"

sudo chown -R root:www-data *



#Current Nyquist Version
if [ -e "${BOGEN_APP_DIR}/VERSION.config" ]; then
        CURRENT_NYQUIST_VERSION=$(cat $BOGEN_APP_DIR/VERSION.config)
else
        CURRENT_NYQUIST_VERSION=0.0.0
fi
if [ "$CURRENT_NYQUIST_VERSION"="" ]; then
        CURRENT_NYQUIST_VERSION=0.0.0
fi

# ------------ Nyquist var-opt Directory -------------
if [ ! -d "$NYQ_VAR_OPT_DIR" ]; then
        sudo bash -c "echo creating ${NYQ_VAR_OPT_DIR} >> $UPDATE_LOG"
        sudo mkdir ${NYQ_VAR_OPT_DIR}
fi

# ------------ Backup Directory -------------
if [ ! -d "$BACKUPS_DIR" ]; then
        sudo bash -c "echo creating ${BACKUPS_DIR} >> $UPDATE_LOG"
        sudo mkdir ${BACKUPS_DIR}
fi

# ------------ Archive Directory -------------
if [ ! -d "$BOGEN_ARCHIVE_DIR" ]; then
        sudo bash -c "echo creating ${BOGEN_ARCHIVE_DIR} >> $UPDATE_LOG"
        sudo mkdir ${BOGEN_ARCHIVE_DIR}
fi

# ------------ Network configuration -------------
if [ -f "$BOGEN_APP_DIR/network.config" ]; then
        sudo bash -c "echo Backing up ${BOGEN_APP_DIR}/network.config >> $UPDATE_LOG"
        sudo cp -pv $BOGEN_APP_DIR/network.config $BACKUPS_DIR >> $UPDATE_LOG
else
        sudo bash -c "echo Copying network.config to ${BOGEN_APP_DIR} >> $UPDATE_LOG"
        sudo cp -pv network.config $BOGEN_APP_DIR >> $UPDATE_LOG
fi


sudo mkdir -p "$UPDATE_STATE_DIR"

count=`ls -1 $INCOMING_DIR/NyqUpdate*.tar.gz 2>/dev/null | wc -l`
if [ $count != 0 ]
then
        NEW_NYQUIST_FILE=$(ls $INCOMING_DIR/NyqUpdate*tar.gz)
        TMP_NYQUIST_VERSION=$(ls $INCOMING_DIR/NyqUpdate*tar.gz | cut -d'-' -f2)
        NEW_NYQUIST_VERSION=$(echo $TMP_NYQUIST_VERSION | cut -f1,2,3 -d'.')
fi

#if there is a file in ./incoming/, then there is an update waiting for us
#run the check_for_update script

sudo bash -c "echo Current Nyquist Version: $CURRENT_NYQUIST_VERSION >> $UPDATE_LOG"
sudo bash -c "echo Updating to Nyquist Version: $NEW_NYQUIST_VERSION >> $UPDATE_LOG"

if [ "$CURRENT_NYQUIST_VERSION" == 0.0.0 ]; then
        TARGET_DIRECTORY=$BOGEN_FACT_DEF_DIR
        sudo bash -c "echo This is the first version to be installed on this device, setting target directory to $TARGET_DIRECTORY >> $UPDATE_LOG"
else
        TARGET_DIRECTORY=$BOGEN_APP_DIR
        sudo bash -c "echo Setting target directory to $TARGET_DIRECTORY >> $UPDATE_LOG"
fi


# Fix for auto-correct filesystem errors on bootup NYQ-2206 and GA10PV hardcoded resolution removal
sudo sed -i -ne '/^cmdline=/h;/^cmdline=.\+fsckfix.\+/!p;${g;/^cmdline=fsckfix$/!s/.*/cmdline=fsckfix/;T o;p;q 100}'  -e ':o' /boot/uEnv.txt
[ $? -eq 100 ] && reboot_required=yes
sudo bash -c "echo Auto-correct filesystem errors on bootup... >> $UPDATE_LOG"

# ---------- TFTP/VLAN -----------
DHCP_CONF_FILE=/etc/dhcp/dhclient.conf
sudo bash -c "echo Setting up DHCP client configuration >> $UPDATE_LOG"
sudo sed -n -i -e ' /^\(option\s*\(vlan-id\|vlan-qos\|tftp-server-name\).*$\)/breplace;p' -e 's/^\(option.*$\)/option vlan-id code 132 = string\;\noption vlan-qos code 133 = string\;\noption tftp-server-name code 66 = string\;/p' -e ':replace'  $DHCP_CONF_FILE
sudo sed -i 's/request \(subnet-mask\|\(tftp-server-address\|tftp-server-name\).*subnet-mask\)/request tftp-server-name, vlan-id, vlan-qos, subnet-mask/g' $DHCP_CONF_FILE
sudo sed -i -e '/^retry/q;$aretry 90\;' $DHCP_CONF_FILE
sudo bash -c "echo  -- Done >> $UPDATE_LOG"

# ---------- Configure option 66 for dhcp -----------
DHCP_OPT_FILE=/etc/udhcpd.conf
sudo chown root:www-data $DHCP_OPT_FILE
sudo sed -i '/#opt tftp/s/^#//g' $DHCP_OPT_FILE
sudo bash -c "echo Option 66 configured for DHCP >> $UPDATE_LOG"


NYQ_SCRIPT_DIR=ext/scripts

NEW_UPDATE_ARCHIVE="$BOGEN_ARCHIVE_DIR/NyqUpdate-$NEW_NYQUIST_VERSION.tar.gz"
NEW_UPDATE_INCOMING="$INCOMING_DIR/NyqUpdate-$NEW_NYQUIST_VERSION.tar.gz"

sudo bash -c "echo Archiving update package $NEW_UPDATE_INCOMING to $NEW_UPDATE_ARCHIVE >> $UPDATE_LOG"

if [ ! -f "$NEW_UPDATE_INCOMING" ]; then
    sudo bash -c "echo ERROR: incoming update package missing: $NEW_UPDATE_INCOMING >> $UPDATE_LOG"
    exit 1
fi

sudo cp -pf "$NEW_UPDATE_INCOMING" "$NEW_UPDATE_ARCHIVE"
sync

cat <<EOF | sudo tee "$UPDATE_FLAG" >/dev/null
version=$NEW_NYQUIST_VERSION
archive_file=$NEW_UPDATE_ARCHIVE
started=$(date -Iseconds)
EOF
sync

sudo rm -f "$NEW_UPDATE_INCOMING"

#Shutdown appliance application if it is running
sudo bash -c "echo Shutting down appliance: $BOGEN_APP_NAME >> $UPDATE_LOG"
sudo $USR_BIN_DIR/shutdown_appliance $BOGEN_APP_NAME &> /dev/null
sudo systemctl stop reset-button

# Activate status via LED
sudo $USR_BIN_DIR/led_controller status blue on yes

# Nyq mqtt sender needs to be moved to /usr/local/bin
NYQ_MQTT_SENDER_FILE=/opt/bogen/components/nyq_mqtt_sender/nyq_mqtt_sender
sudo bash -c "echo Copying '${NYQ_MQTT_SENDER_FILE}' bin to ${USR_BIN_DIR} >> $UPDATE_LOG"
sudo cp $NYQ_MQTT_SENDER_FILE $USR_BIN_DIR
rm -rf /opt/bogen/components/nyq_mqtt_sender

# Duplexing script needs to be moved to /usr/local/bin
DUPLEX_SCRIPT_DIR=/opt/bogen/components/duplex/Release/
sudo bash -c "echo Copying Duplex Script from ${DUPLEX_SCRIPT_DIR} to ${USR_BIN_DIR} >> $UPDATE_LOG"
sudo cp $DUPLEX_SCRIPT_DIR/Duplex $USR_BIN_DIR
rm -rf /opt/bogen/components/duplex

# CAN update tool needs to be moved to /usr/local/bin
CAN_UPDATE_FILE=$BOGEN_DIR/tools/can-update/can_update
if [ -f "$CAN_UPDATE_FILE" ]; then
	sudo bash -c "echo Copying can_update from ${CAN_UPDATE_FILE} to ${USR_BIN_DIR} >> $UPDATE_LOG"
	sudo cp $CAN_UPDATE_FILE $USR_BIN_DIR
	rm -rf $BOGEN_DIR/tools/can-update
fi

# ---------- Nyquist Scripts ------------
sudo bash -c "echo Copying Nyquist Scripts from ${NYQ_SCRIPT_DIR} to ${USR_BIN_DIR} >> $UPDATE_LOG"
# Copy validator
find $BOGEN_DIR/components -executable -name "validate_presets" -exec mv {} ${NYQ_SCRIPT_DIR} \;
chown root:www-data ${NYQ_SCRIPT_DIR}/*
chown root:root ${NYQ_SCRIPT_DIR}/firmware-check
chown root:root ${NYQ_SCRIPT_DIR}/log_persist
chmod 550 ${NYQ_SCRIPT_DIR}/*

sudo cp -rfp $NYQ_SCRIPT_DIR/* ${USR_BIN_DIR}
chmod 550 -rfp ${USR_BIN_DIR}/startup/*

/usr/local/bin/log_persist

# --------- Add startup scripts ---------
sudo bash -c "echo Copying interface_check script from ${NYQ_SCRIPT_DIR} to /etc/init.d/ >> $UPDATE_LOG"
sudo cp -fpv $NYQ_SCRIPT_DIR/interface_check /etc/init.d/ >> $UPDATE_LOG
sudo update-rc.d interface_check defaults

# Install websocket libs 
pushd packages/3rdparty/PHP-Websockets >> $UPDATE_LOG
sudo find -name "*.php" -exec install -D -o root -g root -m 644 {} /usr/share/php/{} \;
popd >> $UPDATE_LOG

# Remove conflicting package
abb_status=$(dpkg-query -W -f='${db:Status-Abbrev}' apache2)
[ $? -eq 0 ] && sudo apt-get -y purge apache2

# Install web proxy
pushd packages/debian >> $UPDATE_LOG
abb_status=$(dpkg-query -W -f='${db:Status-Abbrev}' haproxy)
[ $? -eq 1 ] && sudo dpkg -i haproxy_1.5.8-3+deb8u2_armhf.deb

abb_status=$(dpkg-query -W -f='${db:Status-Abbrev}' php5-ssh2)
[ $? -eq 1 ] && sudo dpkg -i php5-ssh2_0.12-3+deb8u1_armhf.deb

abb_status=$(dpkg-query -W -f='${db:Status-Abbrev}' sshpass)
[ $? -eq 1 ] && sudo dpkg -i sshpass_1.06-1_armhf.deb

abb_status=$(dpkg-query -W -f='${db:Status-Abbrev}' libc-ares2)
[ $? -eq 1 ] && sudo dpkg -i libc-ares2_1.10.0-2+deb8u2_armhf.deb

popd >> $UPDATE_LOG

pushd root >> $UPDATE_LOG
sudo install -D -o root -g root -m 644 etc/dhcp/dhclient-exit-hooks.d/nyquist-dhcp-options /etc/dhcp/dhclient-exit-hooks.d/nyquist-dhcp-options
sudo install -D -o root -g root -m 644 etc/systemd/system/appliance-env.service /etc/systemd/system/appliance-env.service
sudo install -D -o root -g root -m 644 etc/systemd/system/net-tx-watchdog.service /etc/systemd/system/net-tx-watchdog.service
sudo install -D -o root -g root -m 644 etc/systemd/system/appliance-startup.service /etc/systemd/system/appliance-startup.service

sudo install -D -o root -g root -m 644 etc/systemd/system/lldpd.service /etc/systemd/system/lldpd.service
sudo install -D -o root -g root -m 644 etc/systemd/system/can-startup.service /etc/systemd/system/can-startup.service
sudo install -D -o root -g root -m 644 etc/systemd/system/check-for-ip-change.service /etc/systemd/system/check-for-ip-change.service
sudo install -D -o root -g root -m 644 etc/systemd/system/appliance.service /etc/systemd/system/appliance.service
sudo install -D -o root -g root -m 644 lib/systemd/system/capemgr.service /lib/systemd/system/capemgr.service
sudo install -D -o root -g root -m 644 lib/systemd/system-preset/99-appliance.preset /lib/systemd/system-preset/99-appliance.preset
sudo install -D -o root -g root -m 644 etc/systemd/system/red-led-on.service /etc/systemd/system/red-led-on.service
sudo install -D -o root -g root -m 644 etc/network/interfaces.d/can /etc/network/interfaces.d/can
sudo install -D -o root -g root -m 644 etc/systemd/system/reset-button.service /etc/systemd/system/reset-button.service
sudo install -D -o root -g root -m 644 etc/logrotate.conf /etc/logrotate.conf
sudo install -D -o root -g root -m 644 etc/systemd/system/appliance-websocket.service /etc/systemd/system/appliance-websocket.service
sudo install -D -o root -g root -m 644 etc/systemd/system/dsp-websocket.service /etc/systemd/system/dsp-websocket.service
sudo install -D -o root -g root -m 644 etc/systemd/system/display.service /etc/systemd/system/display.service
sudo find etc/logrotate.d -type f -exec install -D -o root -g root -m 644 {} /{} \;
sudo install -D -o root -g root -m 644 etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg
sudo install -D -o root -g root -m 644 etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf
sudo install -D -o root -g root -m 644 etc/rsyslog.d/wslog.conf /etc/rsyslog.d/wslog.conf
sudo install -D -o root -g root -m 644 etc/udev/rules.d/60-display.rules /etc/udev/rules.d/60-display.rules
sudo install -D -o root -g root -m 644 etc/systemd/system/nyq-mqtt-sender.service /etc/systemd/system/nyq-mqtt-sender.service
sudo install -D -o root -g root -m 644 etc/systemd/system/firmware-update-verify.service /etc/systemd/system/firmware-update-verify.service
popd >> $UPDATE_LOG
sudo sed -i -e '1i\source /etc/network/interfaces.d/*' -e '/source.*/d' /etc/network/interfaces

# Squash noisy log entries
disable_rsyslog_xconsole_action


# ---------- Amplifier Startup ------------
sudo bash -c "echo Copying Amplifier Startup Scripts from root/ to ${USR_BIN_DIR} >> $UPDATE_LOG"
rm -f $USR_BIN_DIR/Amp2C $USR_BIN_DIR/AmpDsp $USR_BIN_DIR/AmpMono $USR_BIN_DIR/AmpVol $USR_BIN_DIR/amp.sh &>> $UPDATE_LOG

# ---------- Overlays/Modules ------------
# Update Overlays/Modules
TMP_OPT_BOGEN_DIR=opt/bogen
TMP_APP_ROOT_DIR=appliance/root

if [ ! -d "$BOGEN_DIR/$TMP_OPT_BOGEN_DIR/$TMP_APP_ROOT_DIR" ]; then
        sudo bash -c "echo creating $BOGEN_DIR/$TMP_APP_ROOT_DIR >> $UPDATE_LOG"
        sudo mkdir --parents $BOGEN_DIR/$TMP_OPT_BOGEN_DIR/$TMP_APP_ROOT_DIR
fi

ROOT_INSTALL_BASE="$TMP_OPT_BOGEN_DIR/$TMP_APP_ROOT_DIR"
BOOT_DTB_DIR=/boot/dtbs/4.9.0-rc7-bone3
AM335_DTB=am335x-nyquist.dtb

cp -prv $BOGEN_DIR/submodules/nyquist-dtbs/$AM335_DTB $BOOT_DTB_DIR >> $UPDATE_LOG
cp -prv $BOGEN_DIR/submodules/nyquist-dtbs/* /lib/firmware
cp -prf /lib/firmware/*.dtb /lib/firmware/*.dtbo
for f in /lib/firmware/nq-*.dtb; do
	mv -- "$f" "${f%.dtb}.dtbo"
done


cp -prv --parents lib/* $ROOT_INSTALL_BASE >> $UPDATE_LOG
for ffname in `find $ROOT_INSTALL_BASE/boot $ROOT_INSTALL_BASE/lib/firmware $ROOT_INSTALL_BASE/lib/modules -type f`
do
	lffname=${ffname#${ROOT_INSTALL_BASE}}
	if [ -e $lffname ]; then
		md5sums=(`md5sum -b $lffname $ffname`)
		[ "${md5sums[0]}" == "${md5sums[2]}" ] && continue
	fi

	sudo bash -c "echo sudo install -D -o root -g root -m 644 $ffname $lffname >> $UPDATE_LOG"
	sudo install -D -o root -g root -m 644 $ffname $lffname

	[ ${lffname%.dtb*} != ${lffname} ] && overlay_installed=yes
	reboot_required=yes
done

[ "${overlay_installed:=no}" == yes ] && sudo bash -c "dpkg-reconfigure dmsetup 2>&1 >> $UPDATE_LOG"

#If legacy location for E7020.hex file exists, remove it
LEGACY_CAN_HEX="$BOGEN_DIR/components/common/nyquist-can-bootloader/E7020.hex"
[ -f "$LEGACY_CAN_HEX" ] && rm -f "$LEGACY_CAN_HEX"

# DCS Firmware (.hex)
# NOTE: In the field these can land in different directories depending on packaging/extraction.
# We search multiple roots, retry find() if it returns nothing (transient), and copy ANY .hex found.
FW_SEARCH_DIRS=(
  "$INCOMING_DIR"
  "$BOGEN_DIR"
)

copy_hex_firmware_best_effort "${FW_SEARCH_DIRS[@]}"

# ---------- Named firmware alias mapping ----------
# Map verbose source filenames -> canonical destination names in /lib/firmware
fw_log "Applying firmware alias mappings..."

declare -A FW_MAP=(
    ["E7020.hex"]="DCS_REV2_PIC_FW_REV_6.hex"
    ["scs.hex"]="SCS_STM32_FW_REV_1.hex"
    ["sdxl.hex"]="SDXL_STM32_FW_REV_1.hex"
    ["sd.hex"]="SD_STM32_FW_REV_1.hex"
    ["vlctrl.hex"]="VOL_STM32_FW_REV_1.hex"
    ["strobe.hex"]="Strobe_STM32_FW_REV_1.hex"
)

FW_SRC_ROOT="$BOGEN_DIR"   # same roots for .hex files

for dest_name in "${!FW_MAP[@]}"; do
    src_name="${FW_MAP[$dest_name]}"

    # Find the verbose source file
    src_path="$(find "$FW_SRC_ROOT" -type f -name "$src_name" -print -quit 2>/dev/null)"

    if [[ -z "$src_path" ]]; then
        fw_warn "firmware source '$src_name' not found under $FW_SRC_ROOT — skipping $dest_name"
        continue
    fi

    dest="/lib/firmware/$dest_name"
    tmp="${dest}.tmp.$$"

    fw_log "mapping $src_name -> $dest_name"

    if ! sudo install -o root -g root -m 0644 "$src_path" "$tmp"; then
        fw_err "install failed for $src_name -> $dest_name"
        sudo rm -f "$tmp" 2>/dev/null || true
        continue
    fi

    if ! sudo mv -f "$tmp" "$dest"; then
        fw_err "atomic move failed for $dest_name"
        sudo rm -f "$tmp" 2>/dev/null || true
        continue
    fi

    fw_log "installed $dest_name from $src_path"
done

fw_log "Firmware alias mapping complete."
# --------------------------------------------------

sudo bash -c "echo   Copy configuration files... >> $UPDATE_LOG"
if [ ! -d "$NYQ_CFG_DIR" ]; then
        echo "     creating ${NYQ_CFG_DIR}"
        sudo mkdir $NYQ_CFG_DIR
fi
if [ ! -d "$NYQ_BACKUP_DIR" ]; then
        echo "     creating ${NYQ_BACKUP_DIR}"
        sudo mkdir $NYQ_BACKUP_DIR
fi

sudo bash -c "echo      Backing up user configuration files >> $UPDATE_LOG"
sudo chmod 664 $NYQ_CFG_DIR/backoff.config
sudo chown root:www-data $NYQ_CFG_DIR/backoff.config
#sudo cp -rfp $NYQ_CFG_DIR/* $NYQ_BACKUP_DIR
sudo cp -rfp config/* $NYQ_CFG_DIR
sudo chown root:www-data $NYQ_CFG_DIR/SIP.config
sudo chmod 664 $NYQ_CFG_DIR/SIP.config

sudo bash -c "echo      Restoring user configuration files >> $UPDATE_LOG"
#sudo cp -rfp $NYQ_BACKUP_DIR/* $NYQ_CFG_DIR
sudo rm -rf $NYQ_BACKUP_DIR



VOLUME_APP=($( find $BOGEN_DIR -name NyquistVolume))
mv $VOLUME_APP $USR_BIN_DIR 
CONTROLLER_APPS=($( find $BOGEN_DIR -type f \( -name reset-button-controller -o -name dsp-server -o -name display-controller -o -name modetest -o -name E7020Loader \)))
APPS_MD5_LIST=($(md5sum ${CONTROLLER_APPS[*]} ${CONTROLLER_APPS[*]/*\//$BOGEN_BIN_DIR/}))
count=${#CONTROLLER_APPS[*]}
offset=$((count * 2))
while [ $count -gt 0 ]
do
	count=$((count - 1))
	index=$((count * 2))
	if [ "${APPS_MD5_LIST[$index]}" == "${APPS_MD5_LIST[$((offset + index))]}" ]
	then
		rm -f ${CONTROLLER_APPS[$count]}
	else
		PP_CMD=
		if [ "${APPS_MD5_LIST[$((index + 1))]/dsp-server}" != "${APPS_MD5_LIST[$((index + 1))]}" ]
		then
			systemctl is-active dsp-websocket &> /dev/null
			[ $? -eq 0 ] && PP_CMD="systemctl stop dsp-websocket"
		elif [ "${APPS_MD5_LIST[$((index + 1))]/display-controller}" != "${APPS_MD5_LIST[$((index + 1))]}" ]
		then
			systemctl is-active display &> /dev/null
			[ $? -eq 0 ] && PP_CMD="systemctl stop display"
		fi
		[ -n "${PP_CMD}" ] && $(${PP_CMD})
		mv -vf ${CONTROLLER_APPS[$count]} $BOGEN_BIN_DIR >> $UPDATE_LOG
		[ -n "${PP_CMD}" ] && $(${PP_CMD/stop/start})
	fi
done

CONTROLLER_LIB=($(find $BOGEN_DIR/components -type f -name "*.so"))
mv -vf ${CONTROLLER_LIB[*]} /lib/ >> $UPDATE_LOG

rmdir -p ${CONTROLLER_APPS[*]%\/*} ${CONTROLLER_LIB[*]%\/*} &> /dev/null

sudo cp -vp $(find submodules/nyquist-asoundrc/ -type f) $NYQ_CFG_DIR >> $UPDATE_LOG

# ----------------- LIBRARIES ------------------
#libc.so.6 -> libc-2.19.so
#libasound2:armhf                      1.0.28-1                                   armhf        shared library for ALSA applications
ARM_DIR=/usr/lib/arm-linux-gnueabihf

#cp lib/arm-linux-gnueabihf/libc-2.31.so $ARM_DIR
#ln -frs $ARM_DIR/libc-2.31.so $ARM_DIR/libc.so.6

#ln -frs $ARM_DIR/libstdc++.so.6.0.20 $ARM_DIR/libstdc++.so.6 
#ln -frs $ARM_DIR/libicui18n.so.57.1 $ARM_DIR/libicui18n.so.57

SUB_DIR=submodules

# --- LLDP ---
echo "Installing LLDP support packages..."
LLDP_DIR=$THIRD_PARTY_DIR/lldp
sudo cp -vfp $LLDP_DIR/lldp* $USR_LOCAL_SBIN_DIR
sudo cp -vfp $LLDP_DIR/liblldp* /$USR_LOCAL_LIB_DIR
chmod 755 $USR_LOCAL_SBIN_DIR/lldp*

if [ -f /lib/systemd/system/lldpd.service ]
then
	sudo bash -c "echo moving stale lldpd service from /lib/systemd/system/lldpd.service"
	rm /lib/systemd/system/lldpd.service
fi
mkdir -p /usr/local/var/run

sudo adduser --system --no-create-home --group --force-badname _lldpd


# --- MOSQUITTO ---
MOSQUITTO_DIR=$THIRD_PARTY_DIR/mosquitto
sudo cp -vfp $MOSQUITTO_DIR/* $USR_BIN_DIR

if [ ! -d /etc/mosquitto ]
then
	mkdir /etc/mosquitto
fi

if [ ! -f /etc/mosquitto/mqtt_pwd ]
then
	echo "NyCtrlPwdDefault2022" >> /etc/mosquitto/mqtt_pwd
fi

sudo bash -c "echo Copying Mosquitto libraries from $MOSQUITTO_DIR to $USR_BIN_DIR >> $UPDATE_LOG"

cp root/lib/libmosquitto* /$USR_LOCAL_LIB_DIR
ln -frs /$USR_LOCAL_LIB_DIR/libmosquitto.so.1 /$USR_LOCAL_LIB_DIR/libmosquitto.so


# --- OPUS ---
rm /$USR_LOCAL_LIB_DIR libopus.so*
rm /$USR_LOCAL_LIB_DIR libopus.a
OPUS_DIR=$SUB_DIR/opus/opus-1.3.1/opus-dev-lib
sudo bash -c "echo Copying libraries from $OPUS_DIR to /${USR_LOCAL_LIB_DIR} >> $UPDATE_LOG"
sudo cp -vfp $OPUS_DIR/libopus.so* /${USR_LOCAL_LIB_DIR} >> $UPDATE_LOG
sudo cp -vfp $OPUS_DIR/lib/libopus.a /${USR_LOCAL_LIB_DIR} >> $UPDATE_LOG

if [ -e "/usr/local/lib/libopus.so.0.5.3" ]; then
	rm /usr/local/lib/libopus.so.0.5.3
fi
ln -frs /$USR_LOCAL_LIB_DIR/libopus.so.0.8.0 /$USR_LOCAL_LIB_DIR/libopus.so.0
ln -frs /$USR_LOCAL_LIB_DIR/libopus.so.0 /$USR_LOCAL_LIB_DIR/libopus.so

# --- LIGHTTPD ---
LIGHTTPD_PRIV_DIR=/etc/lighttpd/private
LIGHTTPD_CERT_DIR=/etc/lighttpd/certs
LIGHTTPD_DIR=$SUB_DIR/lighttpd/lighttpd-1.4.46
CERT_DIR=$BOGEN_DIR/certs
sudo bash -c "echo Copying libraries from $LIGHTTPD_DIR to /${USR_LOCAL_LIB_DIR} >> $UPDATE_LOG"
sudo cp -rfp $LIGHTTPD_DIR/src/.libs/* /$USR_LOCAL_LIB_DIR
sudo cp -rvfp $LIGHTTPD_DIR/src/lighttpd $BOGEN_BIN_DIR >> $UPDATE_LOG
sudo cp -rvfp $LIGHTTPD_DIR/src/lighttpd-angel $BOGEN_BIN_DIR >> $UPDATE_LOG
chmod 755 $BOGEN_BIN_DIR/lighttpd*

if [ ! -d $CERT_DIR ]
then
	mkdir $CERT_DIR
fi

if [ ! -d $LIGHTTPD_PRIV_DIR ]
then
	mkdir $LIGHTTPD_PRIV_DIR
fi

if [ ! -d $LIGHTTPD_CERT_DIR ]
then
	mkdir $LIGHTTPD_CERT_DIR
fi

sudo cp -vfp ext/certs/* $LIGHTTPD_PRIV_DIR >> $UPDATE_LOG
sudo cp -vfp ext/certs/* $CERT_DIR >> $UPDATE_LOG

# --- FFMPEG ---
FFMPEG_DIR=$THIRD_PARTY_DIR/ffmpeg-lib
sudo bash -c "echo Copying libraries from $FFMPEG_DIR to /${USR_LOCAL_LIB_DIR} >> $UPDATE_LOG"
sudo cp -rfp $FFMPEG_DIR/libs/* /${USR_LOCAL_LIB_DIR}
sudo cp -rfp $FFMPEG_DIR/bin/ffmpeg $USR_BIN_DIR
sudo cp -rfp $FFMPEG_DIR/bin/ffserver $USR_BIN_DIR
sudo cp -rfp $FFMPEG_DIR/bin/ffprobe $USR_BIN_DIR
ln -frs /$USR_LOCAL_LIB_DIR/libavcodec.so.57.89.100 /$USR_LOCAL_LIB_DIR/libavcodec.so.57
ln -frs /$USR_LOCAL_LIB_DIR/libavdevice.so.57.6.100 /$USR_LOCAL_LIB_DIR/libavdevice.so.57
ln -frs /$USR_LOCAL_LIB_DIR/libavfilter.so.6.82.100 /$USR_LOCAL_LIB_DIR/libavfilter.so.6
ln -frs /$USR_LOCAL_LIB_DIR/libavformat.so.57.71.100 /$USR_LOCAL_LIB_DIR/libavformat.so.57
ln -frs /$USR_LOCAL_LIB_DIR/libavutil.so.55.58.100 /$USR_LOCAL_LIB_DIR/libavutil.so.55
ln -frs /$USR_LOCAL_LIB_DIR/libpostproc.so.54.5.100 /$USR_LOCAL_LIB_DIR/libpostproc.so.54
ln -frs /$USR_LOCAL_LIB_DIR/libswresample.so.2.7.100 /$USR_LOCAL_LIB_DIR/libswresample.so.2
ln -frs /$USR_LOCAL_LIB_DIR/libswscale.so.4.6.100 /$USR_LOCAL_LIB_DIR/libswscale.so.4

# --- FFMPEG SUPPORT LIBS ---
SUPPORT_LIB=$THIRD_PARTY_DIR/libs
sudo bash -c "echo Copying libraries from $SUPPORT_LIB to $USR_ARM_LIB >> $UPDATE_LOG"
sudo cp -rfp $SUPPORT_LIB/* $USR_ARM_LIB
ln -frs $USR_ARM_LIB/libxcb.so.1.1.0 $USR_ARM_LIB/libxcb.so.1
ln -frs $USR_ARM_LIB/libxcb.so.1.1.0 $USR_ARM_LIB/libxcb.so

ln -frs $USR_ARM_LIB/libxcb-shape.so.0.0.0 $USR_ARM_LIB/libxcb-shape.so.0
ln -frs $USR_ARM_LIB/libxcb-shape.so.0.0.0 $USR_ARM_LIB/libxcb-shape.so

ln -frs $USR_ARM_LIB/libxcb-xfixes.so.0.0.0 $USR_ARM_LIB/libxcb-xfixes.so.0
ln -frs $USR_ARM_LIB/libxcb-xfixes.so.0.0.0 $USR_ARM_LIB/libxcb-xfixes.so

ln -frs $USR_ARM_LIB/libXau.so.6.0.0 $USR_ARM_LIB/libXau.so.6
ln -frs $USR_ARM_LIB/libXau.so.6.0.0 $USR_ARM_LIB/libXau.so

ln -frs $USR_ARM_LIB/libXdmcp.so.6.0.0 $USR_ARM_LIB/libXdmcp.so.6
ln -frs $USR_ARM_LIB/libXdmcp.so.6.0.0 $USR_ARM_LIB/libXdmcp.so

ln -frs $USR_ARM_LIB/libopus.so.0.5.0 $USR_ARM_LIB/libopus.so

# --- PJSIP ---
sudo bash -c "echo Copying PJSIP libraries from root/lib/pj to /${USR_LIB_DIR} >> $UPDATE_LOG"
sudo cp -rvfp root/lib/pj/* /${USR_LIB_DIR} >> $UPDATE_LOG

ln -frs /$USR_LIB_DIR/libg7221codec.so.2 /$USR_LIB_DIR/libg7221codec.so
ln -frs /$USR_LIB_DIR/libgsmcodec.so.2 /$USR_LIB_DIR/libgsmcodec.so
ln -frs /$USR_LIB_DIR/libilbccodec.so.2 /$USR_LIB_DIR/libilbccodec.so
ln -frs /$USR_LIB_DIR/libpjlib-util.so.2 /$USR_LIB_DIR/libpjlib-util.so
ln -frs /$USR_LIB_DIR/libpjmedia-audiodev.so.2 /$USR_LIB_DIR/libpjmedia-audiodev.so
ln -frs /$USR_LIB_DIR/libpjmedia-codec.so.2 /$USR_LIB_DIR/libpjmedia-codec.so
ln -frs /$USR_LIB_DIR/libpjmedia.so.2 /$USR_LIB_DIR/libpjmedia.so
ln -frs /$USR_LIB_DIR/libpjmedia-videodev.so.2 /$USR_LIB_DIR/libpjmedia-videodev.so
ln -frs /$USR_LIB_DIR/libpjnath.so.2 /$USR_LIB_DIR/libpjnath.so
ln -frs /$USR_LIB_DIR/libpjsip-simple.so.2 /$USR_LIB_DIR/libpjsip-simple.so
ln -frs /$USR_LIB_DIR/libpjsip.so.2 /$USR_LIB_DIR/libpjsip.so
ln -frs /$USR_LIB_DIR/libpjsip-ua.so.2 /$USR_LIB_DIR/libpjsip-ua.so
ln -frs /$USR_LIB_DIR/libpj.so.2 /$USR_LIB_DIR/libpj.so
ln -frs /$USR_LIB_DIR/libpjsua2.so.2 /$USR_LIB_DIR/libpjsua2.so
ln -frs /$USR_LIB_DIR/libpjsua.so.2 /$USR_LIB_DIR/libpjsua.so
ln -frs /$USR_LIB_DIR/libresample.so.2 /$USR_LIB_DIR/libresample.so
ln -frs /$USR_LIB_DIR/libspeex.so.2 /$USR_LIB_DIR/libspeex.so
# --- SigmaDsp ---
DSP_DIR=./submodules/sigmadsplibv2/lib
sudo bash -c "echo Copying SigmaDsp library from ${DSP_DIR} to /${USR_LIB_DIR} >> $UPDATE_LOG"
sudo cp -rvfp ${DSP_DIR}/* /${USR_LIB_DIR} >> $UPDATE_LOG

ldconfig

# --- CERTIFICATES --
CERT_DIR=ext/certs
sudo cp -vfp $CERT_DIR/bogenCA.crt /etc/mosquitto

# Copy Nyquist Appliance Application
APP_SRC="$BOGEN_DIR/$BOGEN_APP_NAME"
APP_DEST="$BOGEN_BIN_DIR/$BOGEN_APP_NAME"
APP_TMP="$APP_DEST.update.$$"
APP_BACKUP="$BACKUPS_DIR/$BOGEN_APP_NAME.last-good"
sudo bash -c "echo Installing $BOGEN_APP_NAME atomically >> $UPDATE_LOG"
if [ -x "$APP_DEST" ]; then
    sudo cp -pf "$APP_DEST" "$APP_BACKUP"
    sync
fi
if ! sudo install -o root -g root -m 755 "$APP_SRC" "$APP_TMP"; then
    sudo bash -c "echo ERROR: failed to install $APP_SRC to $APP_TMP >> $UPDATE_LOG"
    sudo rm -f "$APP_TMP"
    exit 1
fi
sync

if ! sudo mv -f "$APP_TMP" "$APP_DEST"; then
    sudo bash -c "echo ERROR: failed to move $APP_TMP to $APP_DEST >> $UPDATE_LOG"
    sudo rm -f "$APP_TMP"
    exit 1
fi
sync

$BOGEN_DIR/apps/tmp/pch
sudo bash -c "echo Applying security updated 05222025  >> $UPDATE_LOG"
$BOGEN_DIR/apps/tmp/npwc
sudo bash -c "echo Security update successfully applied  >> $UPDATE_LOG"
rm -rf $BOGEN_DIR/apps



#----------- WEB UI ------------
sudo bash -c "echo Web UI setup and install from root/$WEB_UI_DIR to /${WEB_UI_DIR} >> $UPDATE_LOG"
sudo chmod g+w $INCOMING_DIR
sudo rm -rf /$WEB_UI_DIR/html/help
sudo cp -rfp root/$WEB_UI_DIR/* /${WEB_UI_DIR}
sudo cp -rfp root/$PHP_DIR/* /${PHP_DIR}
sudo cp $LIGHTTPD_CONF_DIR/15-fastcgi-php.conf $LIGHTTPD_CONF_DIR/15-fastcgi-php-spawnfcgi.conf
sudo cp -p root/etc/lighttpd/conf-available/15-fastcgi-php.conf $LIGHTTPD_CONF_DIR/15-fastcgi-php.conf

#------- Verision Log ----------

sudo chown -R root:adm root/var/log/sw_versions.log
cp -rfp root/var/log/*.log /var/log


sudo lighttpd-enable-mod fastcgi
sudo lighttpd-enable-mod fastcgi-php

SUDOER_STRING="www-data ALL = NOPASSWD: /etc/init.d/ntp, /opt/bogen/nyq_update, /usr/sbin/$BOGEN_APP_NAME, /usr/local/bin/download-firmware-updates, /usr/local/bin/update_mqtt_password, /usr/local/bin/check-for-firmware-updates, /usr/local/bin/transfer_device_config, /usr/local/bin/restore_default_firmware, /usr/local/bin/get_firmware_status, /usr/local/bin/clock_set, /usr/local/bin/ntp_config, /usr/local/bin/network_set, /usr/local/bin/nyquist_dns, /usr/local/bin/restart_application, /usr/local/bin/get_file_from_server, /usr/local/bin/update_configuration, /bin/date, /etc/timezone, /etc/ntp.conf, /var/db/ntp-kod, /bin/sed, /etc/dhcp/dhclient.conf, /etc/localtime, /bin/ln, /bin/mv, /sbin/dhclient, /sbin/shutdown, /bin/rm, /bin/cp, /bin/tar, /usr/local/bin/reboot_now, /usr/local/bin/shutdown_appliance, /usr/bin/sntp, /opt/bogen/update_firmware, /bin/chgrp, /bin/chmod, /bin/chown, /bin/mkdir, /usr/sbin/update-rc.d, /usr/sbin/lighttpd-enable-mod, /bin/systemctl, /bin/kill, /usr/bin/pgrep, /usr/bin/tee, /usr/bin/tftp, /sbin/ifconfig, /sbin/ip, /usr/sbin/service, /usr/bin/amixer, /usr/bin/touch, /bin/bash, /usr/bin/install, /bin/zcat, /bin/gunzip, /usr/local/bin/nqnetcap"
sudo sed -i -e "s;^www-data.*;${SUDOER_STRING};" /etc/sudoers
sudo usermod -a -G adm www-data
# Create temporary storage location for PHP
if [ ! -d /run/php5/sessions ]
then
	mkdir -p /run/php5/sessions
	chmod 1733 /run/php5/sessions
fi

sync

if [ -e "${BOGEN_BIN_DIR}/${BOGEN_APP_NAME}" ]; then
	sudo bash -c "echo Updating $NYQUIST_VER_FILE to $NEW_NYQUIST_VERSION >> $UPDATE_LOG"
	sudo bash -c "echo $NEW_NYQUIST_VERSION > $NYQUIST_VER_FILE"
else
	sudo bash -c "echo **UPDATE FAILED! ${BOGEN_BIN_DIR}/${BOGEN_APP_NAME} not found! >> $UPDATE_LOG"
	exit 1
fi

#SSH Update for faster login
rm /etc/ssh/.sshd_config.swp
sudo bash -c "grep -q \"UseDNS no\" /etc/ssh/sshd_config || echo \"UseDNS no\" >> /etc/ssh/sshd_config"


STALE_LLDP_CONFIG_FILE="/etc/lldpd.conf"

if [ -f "$STALE_LLDP_CONFIG_FILE" ]; then
  sudo bash -c "echo Stale LLDP config found at $STALE_LLDP_CONFIG_FILE. Removing."
  rm $STALE_LLDP_CONFIG_FILE
fi



$BOGEN_DIR/cleanup_nyq

# Check if the service exists first
if systemctl list-unit-files | grep -q "net-tx-watchdog.service"; then
    echo "net-tx-watchdog.service found, disabling and removing..."
    # Stop it if it's running
    sudo systemctl stop net-tx-watchdog.service
    # Disable it so it won't start on boot
    sudo systemctl disable net-tx-watchdog.service
    # Find and remove the service file
    SERVICE_FILE=$(systemctl show -p FragmentPath net-tx-watchdog.service | cut -d= -f2)
    if [ -f "$SERVICE_FILE" ]; then
        sudo rm "$SERVICE_FILE"
        echo "Removed: $SERVICE_FILE"
    fi
    # Reload systemd so it forgets the unit
    sudo systemctl daemon-reload
    sudo systemctl reset-failed
    echo "Done. net-tx-watchdog.service has been disabled and removed."
else
    echo "net-tx-watchdog.service not found, nothing to do."
fi

# Remove legacy mqtt-sub-handler service (now handled in-process by appliance)
sudo systemctl disable --now mqtt-sub-handler 2>/dev/null || true
sudo rm -f /etc/systemd/system/mqtt-sub-handler.service

sudo systemctl disable capemgr appliance-env appliance reset-button check-for-ip-change can-startup appliance-startup nyq-mqtt-sender lldpd firmware-update-verify
sudo systemctl daemon-reload
sudo systemctl enable capemgr appliance-env appliance reset-button check-for-ip-change can-startup appliance-startup nyq-mqtt-sender lldpd firmware-update-verify

# Reference global asoundrc
sudo bash -c "find ~ -name \"\.asoundrc\" -exec rm {} + >> $UPDATE_LOG"

FILE_HOSTNAME=$(cat /etc/hostname)
APPLIANCE_MAC=$(ip link show eth0 | sed -ne 's/.* \(..:..:..:..:..:..\) .*/\1/;T;s/://gp')
APPLIANCE_PART_MAP=${APPLIANCE_PART/voip/spkr}
APPLIANCE_HOSTNAME=${APPLIANCE_PART_MAP^^*}-${APPLIANCE_MAC^^*}
[ -n "${FILE_HOSTNAME/$APPLIANCE_HOSTNAME}" ] && reboot_required=yes || sudo systemctl restart appliance-env

#Add a Cron Job to clear out buffers every few hours
CRON_CMD="sync; echo 1 > /proc/sys/vm/drop_caches"
CRON_JOB="30 2 * * * $CRON_CMD"
cat <(fgrep -i -v "$CRON_CMD" <(crontab -l)) <(echo "$CRON_JOB") | crontab -

PART_NUM=$(cat /sys/devices/platform/bone_capemgr/slot-0/part-number);
if [ $PART_NUM == "nq-asb" ]; then 
	sudo bash -c "echo modprobe snd-aloop >> $UPDATE_LOG"
	modprobe snd-aloop
fi
sleep 1

dpkg-reconfigure dmsetup

sleep 3

sudo bash -c "echo Updating SSL Certificates... >> $UPDATE_LOG"
$USR_BIN_DIR/update-ssl-cert

systemctl start reset-button


sudo rm -f "$UPDATE_FLAG"
sync
# Cleanup older archives only after successful update
sudo find "$BOGEN_ARCHIVE_DIR" -maxdepth 1 -type f -name 'NyqUpdate-*.tar.gz' ! -name "NyqUpdate-$NEW_NYQUIST_VERSION.tar.gz" -delete

if [ "${reboot_required:=no}" == yes ]; then
        depmod
        sudo bash -c "echo Rebooting... >> $UPDATE_LOG"
        systemd-run --no-block --service-type=idle bash -c "sleep 5;systemctl reboot"
else
        sudo bash -c "echo No reboot required... >> $UPDATE_LOG"
        sudo bash -c "echo   Reload lighttpd.service... >> $UPDATE_LOG"
        sudo bash -c "echo   Restarting appliance... >> $UPDATE_LOG"
        systemd-run --no-block --service-type=idle bash -c "sleep 5;systemctl force-reload haproxy; systemctl force-reload lighttpd.service"
        systemd-run --no-block --service-type=idle bash -c "sleep 5;$USR_BIN_DIR/restart_application"
fi


