#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ABSOLUTE_ME="$DIR/$(basename "${BASH_SOURCE[0]}")"

if [ "$EUID" -ne 0 ]; then
    sudo $ABSOLUTE_ME
    SUDO_RET="$?"
    exit $SUDO_RET
fi

function doReset {
    echo "Stopping tools..."
    $DIR/gfStopAll

    echo "Resetting box..."
    rm -rf /opt/grassfish/data
    mkdir -p /opt/grassfish/data
    if [ -d /opt/grassfish/datatemplate ]; then
        cp -r /opt/grassfish/datatemplate/* /opt/grassfish/data/
    fi
    chown -R 1000:1000 /opt/grassfish/data
    chmod -R 775 /opt/grassfish/data

    echo "Rebooting..."
    reboot
}

function askContinue {
    read -p "Are you sure you want to reset this box (y/n)? " choice
    case "$choice" in 
        y|Y ) systemd-run --no-block "$ABSOLUTE_ME" -f;;
        n|N ) exit 1;;
        * ) askContinue;;
    esac
}

if [ "$1" != "-f" ]; then
    askContinue
else
    doReset
fi
