#!/bin/bash
##
#
# Vaisala software source code file
#
# Copyright (c) Vaisala Oyj 2015. All rights reserved.
#
##
set -ueo pipefail

SRV_DIR="/srv/vaisala/radarsw/geoserver"
INSTALL_DIR="/usr/vaisala/radarsw/geoserver"
SAMPLE_DATA_DIR="$INSTALL_DIR/sample_data"

GWC_CACHE_DIR="$SRV_DIR/gwc_cache"
DATA_DIR="$SRV_DIR/data"
TMP_DIR="$SRV_DIR/tmp"
GEOTOOLS_EPSG_HSQL_DIR="$SRV_DIR/geotools_epsg-hsql"

GEOSERVER_USER="radargeo"
DISTRO_GROUP="radarsw"

usage() {
    echo "rsw-geoserver-reset-disk-state"  >&2
    echo "  Reset GeoServer and GeoWebCache disk directories to their package installation state." >&2
    echo "" >&2
    echo "Pass in -y to forcefully remove the current directories on disk." >&2
}

help() {
    echo "Pass in -y as the first argument if you really want to remove all the data from GeoServer and GWC on-disk directories." >&2
}

# Guarding this can only be run as root.
if [ "$(whoami)" != "root" ]; then
    echo "Must be root to run this script." >&2
    exit 77
fi

delete="no"
while getopts ":yh" opt; do
    case $opt in
	h)
	    usage
	    exit 0
	    ;;
	y)
	    delete="yes"
	    ;;
	\?)
	    echo "Invalid option: -$OPTARG." >&2
	    usage
	    exit 1
	    ;;
    esac
done

if [[ "$delete" != "yes" ]]; then
    help
    exit 1
fi

for dir in "$GWC_CACHE_DIR" "$TMP_DIR" "$GEOTOOLS_EPSG_HSQL_DIR" "$DATA_DIR"; do
    echo "Removing '$dir'." >&2
    rm -rf "$dir" > /dev/null 2>&1
done

for dir in "$GWC_CACHE_DIR" "$TMP_DIR" "$GEOTOOLS_EPSG_HSQL_DIR"; do
    mkdir -vp "$dir"
    chown -R $GEOSERVER_USER:$DISTRO_GROUP "$dir"
    find "$dir" -type d -exec chmod 0755 {} \;
    find "$dir" -type f -exec chmod 0644 {} \;
done


echo "Copying '$SAMPLE_DATA_DIR' to '$DATA_DIR'." >&2
cp -r "$SAMPLE_DATA_DIR" "$DATA_DIR"
chown -R $GEOSERVER_USER:$DISTRO_GROUP "$DATA_DIR"
find "$DATA_DIR" -type d -exec chmod 0755 {} \;
find "$DATA_DIR" -type f -exec chmod 0644 {} \;