#!/bin/sh

if [ "$(uname)" != "Linux" ]; then
    echo "This script is for Linux."
    exit 1
fi

echo "=== Asset UPnP installer ==="

PROFILE="$HOME/.AssetUPnP"

CONFIGLINK="$PROFILE/AssetConfigLink.txt"

mkdir -p ~/bin || exit 1

TARGET=~/bin/AssetUPnP
RUNME=$TARGET/AssetUPnP

echo "Installing version:"
cat bin/Versions/Asset-UPnP.txt

if [ -f "$RUNME" ]; then
	echo "Upgrading from:"
	cat "$TARGET/Versions/Asset-UPnP.txt"

    "$RUNME" --shutdown
fi

rm -f /tmp/AssetReg.bin

if [ -f "$TARGET/AssetReg.bin" ] && ! [ -f bin/AssetReg.bin ]; then
	mv "$TARGET/AssetReg.bin" /tmp/AssetReg.bin
fi

rm -rf "$TARGET" || exit 1
cp -r ./bin "$TARGET" || exit 1

if [ -f /tmp/AssetReg.bin ] && ! [ -f "$TARGET/AssetReg.bin" ]; then
	mv /tmp/AssetReg.bin "$TARGET/AssetReg.bin"
fi


CRONTAB=/tmp/asset-crontab.txt

echo "Updating crontab..."
# NOTE some distros fail with "no crontab for user"
# ignore errors, just write a blank crontab.txt if so
crontab -l 2>/dev/null | grep -F -v "$TARGET" > "$CRONTAB"
echo @reboot "$RUNME" >> "$CRONTAB"
crontab "$CRONTAB"
rm -f "$CRONTAB"

rm -f "$CONFIGLINK"

echo "Starting Asset..."

"$RUNME" 2>/dev/null >/dev/null &

while ! [ -f "$CONFIGLINK" ]
do
    sleep 1
done

echo "Configuration page:"
cat "$CONFIGLINK"
echo

echo "Finished."
echo "Asset installed in: $TARGET"
