#!/bin/sh

# Generated on Fri 27 Feb 2026 11:30:21 AM CET at krn.prima.lan by root using opk_install.sh as template.

# Send to stdout, but also copy to log file.
out() {
	echo -en "$*" | tee -a "$UPGRADE_LOG"
}

DELIM="##############################################################################"
EASY_VERSION="3.6.17"
UPGRADE_LOG=/tmp/upgrade.txt
CLEANDB=$1
: ${CLEANDB:="0"}
export PATH=/usr/local/bin:/usr/bin:/bin


rm -f /var/local/upgrade.txt
date +%s > /var/local/upgrade.txt

rm -f "$UPGRADE_LOG"
out "Starting upgrade...\n"
out "Executing: $0 $@\n"

out "############### Packet version: 3.6.17 ###############\n"
out "Checking correct CPU type...\n"
CPU_TYPE=`uname -a`

out "Check correct procesor type...\n"
case "$CPU_TYPE" in
	*armv7*)
		out "CPU type armv71, hardware version Alpha 3, $CPU_TYPE\n"
		out "Remount filesystem to READ WRITE\n"
		mount -o remount,rw /
		REINSTALL_FLAG=--force_reinstall
		INSTALL_PROXY=true
		PREPARE_PYTHON_JAIL=true
		;;
esac

out "Checking if replicator is running... "
( ps ax 2>/dev/null; ps; ) | grep [r]eplicator > /dev/null && { REPLICATOR_UP=1; out "running\n"; } || { REPLICATOR_UP=0; out "not running\n"; }

MAC=$( cat /sys/class/net/eth0/address )
if [ $REPLICATOR_UP -eq 1 ]; then
	out "Finding HwID for $MAC... "
	EVNT_HWID=`rtest sql --retries=3 "SELECT HwID FROM Hardware WHERE UPPER(HwMac) = UPPER('$MAC') AND HwType=100 AND HwDeleted=0 LIMIT 1;" | awk -F\" 'NR==2{print $2}'`
	out "HwID is '$EVNT_HWID'.\n"
fi

if [ $REPLICATOR_UP -eq 1 ]; then
	out "Finding local time from DB... "
	TIME_UTC=$( rtest sql --retries=3 "SELECT strftime('%s', 'now', 'localtime');" | tail -1; )
	TIME=${TIME_UTC:4:10}
	out "Local time from DB is '$TIME_UTC'.\n"
fi

if [ $REPLICATOR_UP -eq 1 ]; then
	out "Checking correct processor type... "
	case "$CPU_TYPE" in
		*arm*)
			out "CPU type arm = OK\n"
			EVENT_QUERY="INSERT INTO Events (EvntDateTime, EvntDscID, UsrID, HwID, EvntData) VALUES($TIME, 2008, 0, $EVNT_HWID, \"Version: 3.6.17\");"
			rtest sql --retries=3 "$EVENT_QUERY"
			;;
		*)
			out "CPU type ERROR: $CPU_TYPE expected ARM.\n"
			EVENT_QUERY="INSERT INTO Events (EvntDateTime, EvntDscID, UsrID, HwID, EvntData) VALUES($TIME, 2003, 0, $EVNT_HWID, \"Wrong CPU type ($CPU_TYPE) expected arm\");"
			rtest sql --retries=3 "$EVENT_QUERY"
			exit $LINENO
			;;
	esac
fi

out "Moving firwmare to private folder... "
/bin/mkdir -p /www/firmware
[ -f /www/pages/Nova/assets/firmware.tar ] && /bin/mv -f /www/pages/Nova/assets/firmware.tar /www/firmware/
[ -f /www/pages/Nova/assets/upgrade.tar ] && /bin/mv -f /www/pages/Nova/assets/upgrade.tar /www/firmware/
out "OK.\n"

out "REINSTALL_FLAG is set to \"$REINSTALL_FLAG\".\n"

if [ -f /home/python/default_script ]; then
	out "Stoping Python script... "
	if [ -f "/var/local/python.pid" ]; then
		/bin/kill -9 `/bin/cat /var/local/python.pid`
	else
		/usr/bin/killall -9 python >/dev/null 2>&1
	fi
	out "Done.\n"
fi

INSTALL_ERROR_MESSAGE=""

out "Stopping daemons...\n"
out "\tWatch Dog...  "; /etc/init.d/wd         stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n";
out "\tLighttpd...   "; /etc/init.d/lighttpd   stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n"; killall -9 sysfcgi.fx >/dev/null 2>&1
out "\tSysHwRWX...   "; /etc/init.d/syshwrwx   stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n"; killall -9 syshwrwx   >/dev/null 2>&1
out "\tReplicator... "; /etc/init.d/replicator stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n"; killall -9 replicator >/dev/null 2>&1
out "\tProxy...      "; /etc/init.d/proxy      stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n"; killall -9 proxy      >/dev/null 2>&1
###################################################################################
# All daemons are stopped now.

out "Installing Replicator.... "
#OUT=`opkg install replicator.opk --force-downgrade $REINSTALL_FLAG 2>&1`
opkg install replicator.opk --force-downgrade $REINSTALL_FLAG 2>&1
if [ $? -eq 0 ]; then
	out "OK.\n"
else
	out "Failed ($RES/$?)!\n$DELIM\n$OUT\n$DELIM\n"
	INSTALL_ERROR_MESSAGE+="Replicator "
fi

out "Installing SysHwRWX... "
OUT=`opkg install syshwrwx.opk --force-downgrade $REINSTALL_FLAG 2>&1`
if [ $? -eq 0 ]; then
	out "OK.\n"
else
	out "Failed!\n$DELIM\n$OUT\n$DELIM\n"
	INSTALL_ERROR_MESSAGE+="SysHwRWX "
fi

out "Installing SysFCGI... "
OUT=`opkg install sysfcgi.fx.opk --force-downgrade $REINSTALL_FLAG 2>&1`
if [ $? -eq 0 ]; then
	out "OK.\n"
else
	out "Failed!\n$DELIM\n$OUT\n$DELIM\n"
	INSTALL_ERROR_MESSAGE+="SysFCGI "
fi

sleep 6 # TODO: Why 6? What are we waiting for? Is there no better way to know when wait is over?
/bin/chmod a+x /www/pages/bin/sysfcgi.fx


case "$CPU_TYPE" in
	*armv7*)
		mount -o remount,rw /
		;;
esac
if [ "$INSTALL_PROXY" = true ]; then
	out "Installing Proxy... "
	OUT=`opkg install proxy.opk --force-downgrade $REINSTALL_FLAG 2>&1`
	if [ $? -eq 0 ]; then
		out "OK.\n"
	else
		out "Failed!\n$DELIM\n$OUT\n$DELIM\n"
		INSTALL_ERROR_MESSAGE+="Proxy "
	fi
	/bin/rm -f /etc/init.d/S*proxy
	/usr/bin/proxy --install 50 > /dev/null 2>&1
	/bin/ln -s /etc/init.d/proxy /etc/init.d/S50proxy
fi
sleep 6 # TODO: Why 6? What are we waiting for? Is there no better way to know when wait is over?

out "Installing WatchDog... "
OUT=`opkg install wd.opk --force-downgrade $REINSTALL_FLAG 2>&1`
if [ $? -eq 0 ]; then
	out "OK.\n"
else
	out "Failed!\n$DELIM\n$OUT\n$DELIM\n"
	INSTALL_ERROR_MESSAGE+="WatchDog "
fi

out "Installing Nova2.0... "
OUT=`opkg install nova20.fx.opk --force-downgrade $REINSTALL_FLAG 2>&1`
if [ $? -eq 0 ]; then
	out "OK.\n"
else
	out "Failed!\n$DELIM\n$OUT\n$DELIM\n"
	INSTALL_ERROR_MESSAGE+="Nova2.0 "
fi

out "Checking and installing timezones packages...\n"
if [ `opkg status tzdata|grep "Package:"|wc -l` == 0 ]; then
	out "\tInstalling tzdata_2011b-r8.0.6_all.ipk\n"
	OUT=`opkg -force-depends install /tmp/timezones/tzdata_2011b-r8.0.6_all.ipk --force-downgrade $REINSTALL_FLAG 2>&1`
fi
if [ `opkg status tzdata-right|grep "Package:"|wc -l` == 0 ]; then
	out "\tInstalling tzdata-right_2011b-r8.0.6_all.ipk\n"
	OUT=`opkg -force-depends install /tmp/timezones/tzdata-right_2011b-r8.0.6_all.ipk --force-downgrade $REINSTALL_FLAG 2>&1`
fi
rm -rf /tmp/timezones

out "Stopping daemons...\n"
out "\tWatch Dog...  "; /etc/init.d/wd         stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n";
out "\tLighttpd...   "; /etc/init.d/lighttpd   stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n"; killall -9 sysfcgi.fx >/dev/null 2>&1
out "\tSysHwRWX...   "; /etc/init.d/syshwrwx   stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n"; killall -9 syshwrwx   >/dev/null 2>&1
out "\tReplicator... "; /etc/init.d/replicator stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n"; killall -9 replicator >/dev/null 2>&1
out "\tProxy...      "; /etc/init.d/proxy      stop >/dev/null 2>&1 && out "OK\n" || out "Failed\n"; killall -9 proxy      >/dev/null 2>&1
###################################################################################
# All daemons are stopped now.

out "Clean /etc/default/hwclock if it is full of UTC=yes.\n"
cat /etc/default/hwclock | sort -u > /etc/default/hwclock.tmp
mv /etc/default/hwclock.tmp /etc/default/hwclock

if [ -d /tmp/CentralAPI ]; then
	out "Update CentralAPI.\n"
	mkdir -p /home/python/CentralAPI
	cp -Rf /tmp/CentralAPI /home/python/
	rm -rf /tmp/CentralAPI
else
	out "No CentralAPI to update.\n"
fi

if [ $CLEANDB = "UseInstallDB" ]; then
	echo "Overwriting DB with empty install DB"
	cp /var/local/install_prima_config.db /var/local/prima_config.db
	cp /var/local/install_prima_events.db /var/local/prima_events.db
fi

rm -f /var/local/versions.txt
opkg status replicator | grep Version >> /var/local/versions.txt
opkg status syshwrwx   | grep Version >> /var/local/versions.txt
opkg status sysfcgi.fx | grep Version >> /var/local/versions.txt
opkg status nova20.fx  | grep Version >> /var/local/versions.txt
opkg status proxy      | grep Version >> /var/local/versions.txt

PYTHON=$( python --version 2>&1 )
if [ "$?" -eq 0 ]; then
	echo "$PYTHON" >> /var/local/versions.txt
else
	echo "NoPythonInstalled" >> /var/local/versions.txt
fi
echo "Version: 3.6.17" >> /var/local/versions.txt

opkg status wd         | grep Version >> /var/local/versions.txt

echo -e "\n--- Installed versions: ---"
REPLICATOR_INS_VER=$( /usr/bin/replicator --version | /usr/bin/awk '/^Version/{print $NF}' )
SYSHWRWX_INS_VER=$( /usr/bin/syshwrwx --version | /usr/bin/awk '/^Version/{print $NF}' )
NOVA20_INS_VER=$( /usr/bin/awk -F\' '/appversion/{print $2}' /www/pages/app/index.html | /usr/bin/awk '{print $2}' )
SYSFCGI_INS_VER=$( /www/pages/bin/sysfcgi.fx --version | /usr/bin/awk '/^Version/{print $NF}' )
PROXY_INS_VER=$( /usr/bin/proxy --version | /usr/bin/awk '/^Version/{print $NF}' )
echo "Replicator installed: $REPLICATOR_INS_VER"
echo "SysHwRWX installed: $SYSHWRWX_INS_VER"
echo "SysFCGI installed: $SYSFCGI_INS_VER"
echo "Nova2.0 installed: $NOVA20_INS_VER"
echo "Proxy installed: $PROXY_INS_VER"

echo -e "\n--- Software revisions ---"
REPLICATOR_REVISION=$( /usr/bin/replicator --version | grep Version | awk -F'@' '{print $3}' | awk '{print $1}' )
SYSHWRWX_REVISION=$( /usr/bin/syshwrwx --version | grep Version | awk -F'@' '{print $3}' | awk '{print $1}' )
SYSFCGI_REVISION=$( /www/pages/bin/sysfcgi.fx --version | tail -n 1 | awk -F'@' '{print $3}' | awk '{print $1}' )
PROXY_REVISION=$( /usr/bin/proxy --version | grep Version | awk -F'@' '{print $3}' | awk '{print $1}' )
echo "Replicator: $REPLICATOR_REVISION"
echo "SysHwRWX: $SYSHWRWX_REVISION"
echo "SysFCGI: $SYSFCGI_REVISION"
echo "Proxy: $PROXY_REVISION"

echo -en "\nPreparing Python jail... "
if [ "$PREPARE_PYTHON_JAIL" = true ]; then
	if [ -x "/home/python/usr/bin/python2.7" ]; then
		echo "Allready prepared."
	else
		echo "Creating..."
		/bin/bash /tmp/preparePythonJail.sh
	fi
fi

echo "Alpha pre-start 3.0 specifics..."
case "$CPU_TYPE" in
	*armv7*)
		echo "CPU type armv71, hardware version Alpha 3.0,$CPU_TYPE"
		echo "Create localtime link"
		/bin/rm /etc/localtime
		/bin/ln -s /var/local/etc/localtime /etc/localtime
		echo "Create startup links"
		/bin/rm -f /etc/init.d/S*replicator_ /etc/init.d/S*syshwrwx_ /etc/init.d/S*wd
		[ -f /etc/init.d/S43replicator ] || /bin/ln -s /etc/init.d/replicator /etc/init.d/S43replicator
		[ -f /etc/init.d/S45syshwrwx ] || /bin/ln -s /etc/init.d/syshwrwx /etc/init.d/S45syshwrwx
		[ -f /etc/init.d/S60wd ] || /bin/ln -s /etc/init.d/wd /etc/init.d/S60wd
		echo "Disable sole getty"
		sed -ri 's/^sole::respawn:/\#sole::respawn:/g' /etc/inittab
		if [ ! -f "/etc/init.d/S11CreateLinks" ]; then
			echo "Move S11CreateLinks to init.d"
			/bin/mv /var/local/S11CreateLinks /etc/init.d/S11CreateLinks
		fi
		if [ ! -L "/www/firmware" ]; then
			echo "Move /www/firmware to RAM."
			/bin/rm -rf /www/firmware
			/bin/rm -rf /tmp/firmware
			/bin/mkdir /tmp/firmware
			/bin/ln -s /tmp/firmware /www/firmware
		fi
	;;
esac

echo -en "\nStarting Replicator... "
/etc/init.d/replicator restart >/dev/null 2>&1
while [ 1 ]; do
	OUT=`rtest sql --retries=0 --limit=1000 "SELECT SetID FROM Settings LIMIT 1;" >/dev/null 2>&1`
	if [ $? -eq 0 ]; then
		echo -e "OK.       "
		break
	else
		sleep 1
	fi
done

echo -n "Starting SysHwRWX... "
/etc/init.d/syshwrwx restart >/dev/null 2>&1 && echo "OK." || echo "Failed."

echo -n "Starting Lighttpd... "
/etc/init.d/lighttpd restart >/dev/null 2>&1 && echo "OK." || echo "Failed."

if [ -f /etc/init.d/proxy ]; then
	echo -n "Starting Proxy... "
	/etc/init.d/proxy restart >/dev/null 2>&1 && echo "OK." || echo "Failed."
fi

echo -n "Starting WatchDog... " && echo "OK." || echo "Failed."
/etc/init.d/wd restart >/dev/null 2>&1

sleep 3 # TODO What are we waiting for?

if [ -f /home/python/default_script ]; then
	echo "Start Python script"
	PYTHON_NAME=`/bin/cat /home/python/default_script | tr -d \" \t\n\r\"`
	if [ -x "/home/python/usr/bin/python2.7" ]; then
		/usr/sbin/chroot /home/python /usr/bin/python -u "$PYTHON_NAME" > /dev/null &
	else
		/usr/bin/python -u /home/python/"$PYTHON_NAME" 2>&1 | /usr/bin/logger &
	fi
	echo "Write Python PID into /home/run/python.pid"
	if [ -x "/bin/pgrep" ]; then
		/bin/pgrep -f `/bin/cat /home/python/default_script` > /var/run/python.pid
	else
		/bin/ps w | /bin/grep `/bin/cat /home/python/default_script` | /bin/grep -v grep | /usr/bin/awk '{print $1}' > /var/run/python.pid
	fi
fi
sleep 1 # TODO What are we waiting for?
sync

echo -e "\nUpgrade end event time..."
TIME_UTC=$( rtest sql "SELECT strftime('%s', 'now', 'localtime');" | tail -1 )
TIME=${TIME_UTC:4:10}

echo "Upgrade end event HwID..."

EVNT_HWID=`rtest sql --retries=3 "SELECT HwID FROM Hardware WHERE UPPER(HwMac) = UPPER('$MAC') AND HwType=100 AND HwDeleted=0 LIMIT 1;" | awk -F\" 'NR==2{print $2}'`

if [ -z "$INSTALL_ERROR_MESSAGE" ]; then
	EVNT_DSC_ID="2007"
	EVENT_DATA="Replicator: $REPLICATOR_INS_VER:$REPLICATOR_REVISION"
	EVENT_DATA="$EVENT_DATA SysHwRWX: $SYSHWRWX_INS_VER:$SYSHWRWX_REVISION"
	EVENT_DATA="$EVENT_DATA SysFCGI: $SYSFCGI_INS_VER:$SYSFCGI_REVISION"
	EVENT_DATA="$EVENT_DATA Nova2.0: $NOVA20_INS_VER"
else
	echo "Upgrade end errors: $INSTALL_ERROR_MESSAGE"
	EVNT_DSC_ID="2002"
	EVENT_DATA=$INSTALL_ERROR_MESSAGE
fi
EVENT_QUERY="INSERT INTO Events (EvntDateTime, EvntDscID, UsrID, HwID, EvntData) VALUES($TIME, $EVNT_DSC_ID, 0, $EVNT_HWID, \"$EVENT_DATA\");"

echo "Upgrade end event query: $EVENT_QUERY"
rtest sql "$EVENT_QUERY"

echo -e "\nRunning ANALYZE (bug #4712)..."
/usr/bin/rtest sql "{local} analyze main"

echo "Removing old Nova and List Editor..."
/bin/rm -f /www/pages/Nova/*.swz
/bin/rm -f /www/pages/Nova/*.swf
/bin/rm -f /www/pages/Nova/AutoVersion.sol
/bin/rm -f /www/pages/Nova/index.html
/bin/rm -f /www/pages/Nova/swfobject.js
/bin/rm -rf /www/pages/ListEditor

echo "Creating WD links (bug #4174)..."
/bin/ln -sf /var/local/test_process.sh /var/local/testsyshwrwx
/bin/ln -sf /var/local/test_process.sh /var/local/testlighttpd

echo "Createing time sync link..."
/bin/ln -sf /var/local/ntp_sync.sh /etc/init.d/S42ntp_sync

echo "Deleting manuals from board (bug #4371)..."
/bin/rm -f /www/pages/Nova/manuals/*.pdf

echo "Setting /etc/resolv.conf link..."
FILE="/etc/resolv.conf"
TMPFILE="/tmp/resolv.conf"
echo "Change $FILE to soft link"
if [ -f $FILE ] ; then
	echo "File $FILE exists"
	if [ ! -L $FILE ] ; then
		echo "File $FILE is NOT a link"
		echo "Copy $FILE to $TMPFILE"
		/bin/mv $FILE $TMPFILE
		echo "Create link"
		/bin/ln -s $TMPFILE $FILE
	else
		echo "File $FILE is a link, nothing to do"
	fi
else
	echo "$FILE DON'T exist"
	echo "Create $TMPFILE and soft link"
	/bin/touch $TMPFILE
	/bin/ln -s $TMPFILE $FILE
fi

echo "Alpha 3.0 final specifics..."
case "$CPU_TYPE" in
	*armv7*)
		echo "Remount filesystem to READ ONLY"
		mount -o remount,ro /
		;;
esac

out "Setting certificate links...\n"
[ -f /etc/ssl/prima.ca.product.chain ]     && { [ -f /etc/ssl/prima.ca.product.chain.crt ] || { /bin/ln -s /etc/ssl/prima.ca.product.chain /etc/ssl/prima.ca.product.chain.crt; /bin/echo 'prima.ca.product.chain exists, /etc/ssl/prima.ca.product.chain.crt link created.'; }; } || /bin/echo 'ERROR! Linking failed [prima.ca.product.chain]'
[ -f /etc/ssl/prima.ca.product.chain.crt ] && { [ -f /etc/ssl/prima.ca.product.chain ]     || { /bin/ln -s /etc/ssl/prima.ca.product.chain.crt /etc/ssl/prima.ca.product.chain; /bin/echo 'prima.ca.product.chain.crt exists, /etc/ssl/prima.ca.product.chain link created.'; }; } || /bin/echo 'ERROR! Linking failed [prima.ca.product.chain.crt]'

out "Cleanup...\n"
/bin/rm -Rf /www/pages/Nova/assets/Firmware
/bin/rm -f /www/pages/Nova/assets/*.opk
/bin/rm -f /www/pages/Nova/assets/install.sh

out "Upgrade finished.\n"
date +%s >> /var/local/upgrade.txt

exit 0
