#!/bin/bash
set -euo pipefail

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

usage() {
    echo "Pass in the path to terrain directory as the first positional argument." >&2
}

if [ $# -ne 1 ]; then
    usage
    exit 1
fi

SRC_DIR="$1"

if [ ! -d "$SRC_DIR" ]; then
    echo "Directory '$SRC_DIR' doesn't exist!" >&2
    usage
    exit 1
fi

echo "Using '$SRC_DIR' as the terrain directory." >&2


GEOSERVER_DATA_DIR="/srv/vaisala/radarsw/geoserver/data"
COVERAGE_DIR="$GEOSERVER_DATA_DIR/coverages"
DEST_DIR="$COVERAGE_DIR/terrain"

SHADE_SRC_DIR="$SRC_DIR/shade_pyramid"
SLOPE_SRC_DIR="$SRC_DIR/slope_pyramid"

SHADE_DEST_DIR="$DEST_DIR/shade_pyramid"
SLOPE_DEST_DIR="$DEST_DIR/slope_pyramid"

for dir in "$SHADE_SRC_DIR" "$SLOPE_SRC_DIR"; do
    if [ ! -d "$dir" ]; then
	echo "Directory '$dir' doesn't exist!" >&2
	usage
	exit 1
    fi
done


mkdir -pv "$DEST_DIR"
rm -rf "$SHADE_DEST_DIR"
rm -rf "$SLOPE_DEST_DIR"

cp -r "$SHADE_SRC_DIR" "$SHADE_DEST_DIR"
echo "'$SHADE_SRC_DIR' copied to '$SHADE_DEST_DIR'." >&2
cp -r "$SLOPE_SRC_DIR" "$SLOPE_DEST_DIR"
echo "'$SLOPE_SRC_DIR' copied to '$SLOPE_DEST_DIR'." >&2

echo "Fixing file permissions..." >&2
chown -R radargeo:radarsw "$COVERAGE_DIR"
find "$COVERAGE_DIR" -type d -exec chmod 0755 {} \;
find "$COVERAGE_DIR" -type f -exec chmod 0644 {} \;

echo "Terrain files done." >&2
