#!/bin/sh
#
# Relocates large data directories to the XDATA partition
#
domove() {

set -e
set -u

SRCPARENT="$1"
SRC="$2"
DESTPARENT="$3"
DEST="$4"

if [ ! -e "$DESTPARENT/$DEST" -a -d "$SRCPARENT/$SRC" -a ! -h "$SRCPARENT/$SRC" ]
then
        echo "mkdir --parents $DESTPARENT"
        mkdir --parents "$DESTPARENT"
        echo "mv $SRCPARENT/$SRC $DESTPARENT"
        mv "$SRCPARENT/$SRC" "$DESTPARENT"
        echo "ln -s $DESTPARENT/$DEST $SRCPARENT"
        ln -s "$DESTPARENT/$DEST" "$SRCPARENT"
fi

return 0

}

mkscratch() {

set -e
set -u

PROJDIR="$1"
XDIR="$2"

if [ -d "$PROJDIR" -a ! -e "$XDIR" ]
then
        echo "mkdir $XDIR"
        mkdir "$XDIR"
        echo "chown smc $XDIR"
        chown smc "$XDIR"
        echo "chgrp smc $XDIR"
        chgrp smc "$XDIR"
fi

return 0

}

set -e
set -u
MYHOME=/home/smc

# verify running as root
CURUSER=`whoami`

if [ "$CURUSER" != "root" ]
then
    echo "This script must be run as root (current user is $CURUSER)"
    exit 1
fi


# make sure the XDATA directory exists and is mounted if there
# is a 3rd partition
MNTDEV=/dev/mmcblk0p3
MNTPT=/mnt/XDATA

if [ -b "$MNTDEV" ]
then
        if [ ! -d "$MNTPT" ]
        then
                echo "Warning: $MNTPT does not exist, it is being created"
                mkdir $MNTPT
        fi

        MOUNTSTR=`mount | grep $MNTDEV`
        MOUNTSTR2=""

        if [ ! -z "$MOUNTSTR" ]
        then
                MOUNTSTR2=`echo $MOUNTSTR | grep $MNTPT`

                if [ -z "$MOUNTSTR2" ]
                then
                        echo "Warning: $MNTDEV is not mounted at $MNTPT, it will be remounted"
                        umount "$MNTDEV"
                else
                        echo "$MNTDEV is already mounted at $MNTPT"
                fi
        fi

        if [ -z "$MOUNTSTR2" ]
        then
                echo "Mounting $MNTDEV at $MNTPT"
                mount $MNTDEV $MNTPT
        fi

        domove "$MYHOME" log "$MNTPT" log
        domove "$MYHOME" sc "$MNTPT" sc
        domove "$MYHOME/roots/200_PPPHost" NewFiles "$MNTPT/PPPHost" NewFiles
        mkscratch "$MYHOME/roots/200_GPSListener" "$MNTPT/GPS"
        mkscratch "$MYHOME/roots/200_MAM" "$MNTPT/MAM"
        mkscratch "$MYHOME/roots/200_Aquatracka" "$MNTPT/AQUAT"
        mkscratch "$MYHOME/roots/200_C3" "$MNTPT/C3"
        mkscratch "$MYHOME/roots/200_ADCP" "$MNTPT/ADCP"
        domove "$MYHOME/roots/200_ADCP" data "$MNTPT/ADCP" data
        domove "$MYHOME/roots/200_ADCP" complete "$MNTPT/ADCP" complete
        mkscratch "$MYHOME/roots/200_ADCP2" "$MNTPT/ADCP2"
        domove "$MYHOME/roots/200_ADCP2" data "$MNTPT/ADCP2" data
        domove "$MYHOME/roots/200_ADCP2" complete "$MNTPT/ADCP2" complete
        mkscratch "$MYHOME/roots/200_Microstrain" "$MNTPT/Microstrain"
        mkscratch "$MYHOME/roots/200_GPSWaves" "$MNTPT/GPSWaves"
        mkscratch "$MYHOME/roots/200_SBGPCTD" "$MNTPT/SBGPCTD"
else
        echo "$MNTDEV does not exist, so storage at $MNTPT is not available"
fi

