#!/bin/bash
export USER=`whoami`
export CURRENT_VERSION=1.8.5
export WAVA_VERSION=`wget -O - -o /dev/null https://repo1.maven.org/maven2/org/brutusin/wava-core/maven-metadata.xml | grep '<release>' | grep -Eow '[0-9\.]*'` 

if [ "$USER" != "root" ]; then
    echo "root user is required to run this script"
    exit 1
fi

if [ "$CURRENT_VERSION" == "$WAVA_VERSION" ]; then
    echo "Current version ($CURRENT_VERSION) is the latest"
    exit 1
fi

echo "Downloading latest version ($WAVA_VERSION)..."
wget -O /tmp/wava-latest-dist.zip "https://repository.sonatype.org/service/local/artifact/maven/content?r=central-proxy&g=org.brutusin&a=wava-core&c=dist&e=zip&v=$WAVA_VERSION" &> /dev/null
if [ $? != 0 ]; then
    echo "Error downloading distribution file: https://repository.sonatype.org/service/local/artifact/maven/content?r=central-proxy&g=org.brutusin&a=wava-core&c=dist&e=zip&v=$WAVA_VERSION"
    exit 1
fi

echo "Decompressing dist file..."
unzip -o /tmp/wava-latest-dist.zip -d /tmp &> /dev/null

if [ -d $WAVA_HOME ]; then
    echo "Checking current configuration..."
    cmp --silent $WAVA_HOME/cfg/wava.json.default /tmp/wava-core-$WAVA_VERSION/cfg/wava.json.default && cp -f $WAVA_HOME/cfg/wava.json /tmp/wava-core-$WAVA_VERSION/cfg/wava.json || echo "Configuration file structure has changed. A manual review of the configuration is required. Old version can be found at $WAVA_HOME/wava-back"
fi

echo "Setting file permissions..."
chmod -R 555 /tmp/wava-core-$WAVA_VERSION

echo "Installing..."
rm -rf /$WAVA_HOME/wava-back
rm -rf /temp/wava-back
mv -f $WAVA_HOME /tmp/wava-back
mkdir -p $WAVA_HOME
mv /tmp/wava-core-$WAVA_VERSION/* $WAVA_HOME
mv -f /tmp/wava-back $WAVA_HOME/wava-back
rm -rf /usr/bin/wava
cp $WAVA_HOME/bin/wava-home-aware /usr/bin/wava

echo "Running..."
wava