#!/bin/sh
#
# (C) Copyright 2018 Axis Communications AB, LUND, SWEDEN

#comment Re-install all packages found on the IV partition,
#comment on which /usr/local is assumed to be mounted.

#comment inform: info level syslog
information() {
	logger -t ${0##*/} -p INFO -- "$*"
}

#comment warning: warning level syslog
warning() {
	logger -t ${0##*/} -p WARNING -- "$*"
}

#comment error: crit level syslog
error() {
	logger -t ${0##*/} -p CRIT -- "$*"
}

#comment Source after the information/warning/error function definitions
#comment to avoid using the default once in /lib/rcscripts/sh/error.sh
#comment since the default functions printf and error() exits.
. /lib/rcscripts/sh/files.sh
. /lib/rcscripts/sh/cmpversions.sh

# Investigate the acap installed at the given part
# Return 0 if a supported acap, 1 otherwise
_is_supported_acap() {
	local _sedexpr= REQEMBDEVVERSION=

	# Note:
	# The package.conf file is never sourced in this script, so it is
	# safe to keep the REQEMBDEVVERSION as a local variable here

	# Does it exist and does it even have a package.conf file
	[ -d $1 ] && [ -r $1/package.conf ] || return 1

	# Is it possible to install using legact scripts; Not a 3.0 acap
	eval _sedexpr='/REQEMBDEVVERSION=/!d'
	_var=$(cat $1/package.conf | sed "$_sedexpr" ) || {
		warning "No REQEMBDEVVERSION for $1; Handling it using legacy scripts."
		return 0
	}
	# Use eval to easily handle all variants of quotes
	eval $_var
	compare_vers $REQEMBDEVVERSION lt "3.0" || return 1
}

# Loop through the directory list of /usr/local/packages and re-install
# all application directories containing a package.conf file
restore_acap_installations() {
	local dirs=/usr/local/packages/* origin=$PWD d start
	local name= reload_httpd=no startlist=
	local tmp_addon_dir=/tmp/addon finalize_file=finalize

	information "Looking for acap applications to restore"
	for d in $dirs; do
		[ $d != "$dirs" ] || break
		if _is_supported_acap $d && cd $d; then
			name=${d##*/}
			if eval PATH=/usr/sbin:/sbin:$PATH install-package.sh reinstall >$d/reinstall.log.tmp 2>&; then
				information "Successfully restored $name installation"
				reload_httpd=yes
			else
				warning "Failed to restore $name installation"
			fi
			fsynced_write_or_cleanup $d/reinstall.log.tmp $d/reinstall.log
			! systemctl --quiet is-enabled sdk$name >/dev/null 2>&1 || startlist="$name $startlist"
		fi
	done

	if [ "$reload_httpd" = yes ]; then
		[ -d $tmp_addon_dir ] || mkdir $tmp_addon_dir || warning "Failed create $tmp_addon_dir"
		>$tmp_addon_dir/$finalize_file || warning "Failed create $tmp_addon_dir/$finalize_file"
	fi

	cd $origin 2>&1 || :
	echo "$startlist"
}

acapstostart=$(restore_acap_installations)
echo "$acapstostart"