#!/bin/sh

# Copyright (c) 2016, CZ.NIC, z.s.p.o. (http://www.nic.cz/)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#    * Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#    * Neither the name of the CZ.NIC nor the
#      names of its contributors may be used to endorse or promote products
#      derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL CZ.NIC BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

UPDATER_CONFIG=/etc/updater/auto.lua # Automatic updater configuration file
OPKG=/bin/opkg-cl # Path to opkg
LOCAL_STORE=/usr/share/updater/local-pkgs

ARGS=""
EXC=0

OPERATION="n"
while [ "$1" ]; do
	case "$1" in
		install)
			OPERATION="i"
			break
			;;
		remove)
			OPERATION="r"
			break
			;;
		*)
			ARGS="$ARGS $1"
			;;
	esac
	shift
done
shift

if [ "$OPERATION" = "n" ]; then
	# Not install or remove operation
	$OPKG $ARGS $@
	exit $?
fi


PACKAGES=""
while [ "$1" ]; do
	if [ "`echo "$1" | sed 's/^-/+/'`" != "$1" ]; then # ignore options
		ARGS="$ARGS $1"
		shift
		continue
	fi
	PACKAGES="$PACKAGES
	$1"
	shift
done

# As first takes name of package to be added to config file. As optional second
# argument it takes path to package content.
config_add_pkg() {
	if [ -n "$2" ]; then
		mkdir -p "$LOCAL_STORE"
		cp "$2" "$LOCAL_STORE" # Move content to local store
		CONT=$LOCAL_STORE/$(basename "$2")
		echo "Package \"$1\" { content = \"file://$CONT\" }" >>"$UPDATER_CONFIG"
	fi
	echo "Install \"$1\"" >>"$UPDATER_CONFIG"
}

# Takes single argument, name of package to be removed from config
config_clean_pkg() {
	# Cleanup content from local store
	CONT=`grep -e "^Package \"$1\"" "$UPDATER_CONFIG" | sed -n 's/content="file:\/\/\([^"]*\)"/\1/p'`
	if [ -n "$CONT" ] && [ -f "$CONT" ]; then
		rm -f "$CONT"
	fi
	# Remove all Install and Package fields
	sed -e "/^Install \"$1\"/d;/^Package \"$1\"/d" -i "$UPDATER_CONFIG"
}

install() {
	PKG="$1"
	if ! $OPKG $ARGS install "$PKG"; then
		# opkg failed, probably some problem with package. Lets not change anything
		EXC=255
		return
	fi
	# Do additional steps for local files
	if `echo "$PKG" | grep -q -E '.*(\.ipk|\.deb)$'`; then
		# Source package name from package it self
		PKGCONTENT=$PKG
		TMPDIR1=`mktemp -d /tmp/updater-XXXXXX`
		tar -xzf "$PKGCONTENT" -C "$TMPDIR1"
		TMPDIR2=`mktemp -d /tmp/updater-XXXXXX`
		tar -xzf "$TMPDIR1/control.tar.gz" -C "$TMPDIR2"
		PKG=`sed -ne 's/^Package:[ ]*\([^ ]*\).*/\1/p' "$TMPDIR2/control"`
		rm -rf "$TMPDIR1" "$TMPDIR2"
	fi
	# Clean old lines for this package from config file
	config_clean_pkg "$PKG"
	# Add package to config file
	config_add_pkg "$PKG" "$PKGCONTENT"
}

remove() {
	if ! $OPKG $ARGS remove "$1"; then
		# opkg failed. But continue anyway
		EXC=255
	fi
	config_clean_pkg "$1"
}


# Check if $UPDATER_CONFIG exists. Otherwise create.
if [ ! -f "$UPDATER_CONFIG" ]; then
	echo "-- A file with auto-generated Install commands. Do not edit." > "$UPDATER_CONFIG"
fi

echo "$PACKAGES" | sed '1d' | while read P; do
	case "$OPERATION" in
		i) # Install
			install "$P"
			;;
		r) # Remove
			remove "$P"
			;;
	esac
done
exit $EXC
