#!/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

# 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= autofile=/etc/addon/conf/acapautostart
	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 [ -d $d ] && cd $d && [ -r $d/package.conf ]; 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 || startlist="$startlist $name"
		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
	rm -f $autofile.tmp
	[ ! -f $autofile ] || cp $autofile $autofile.tmp ||
		error "Failed to keep existing autostart file"
	for start in $startlist; do
		echo $start
	done >>$autofile.tmp
	[ ! -f $autofile.tmp ] || fsynced_write_or_cleanup $autofile.tmp $autofile

	cd $origin 2>&1 || :
}

restore_acap_installations