#!/bin/bash
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

set -eux
set -o pipefail

SCRIPT_NAME=$(basename $0)
SCRIPT_HOME=$(dirname $0)

function show_options () {
    echo "Usage: $SCRIPT_NAME [options] <path>"
    echo
    echo "Register <path> as a state path."
    echo
    echo "This will register path as being part of the state of the machine."
    echo "If there is content at <path> it will be moved to "
    echo "/var/lib/use-ephemeral/<path>."
    echo
    echo "Paths are recorded in /var/lib/use-ephemeral/stateful-paths."
    echo
    echo "Options:"
    echo "    --leave-symlink -- create a symlink from <path> to /mnt/state/<path>."
    echo
    exit $1
}

LEAVE_SYMLINK=""

TEMP=`getopt -o h -l help,leave-symlink -n $SCRIPT_NAME -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        --leave-symlink) LEAVE_SYMLINK="true"; shift 1 ;;
        -h | --help) show_options 0;;
        --) shift ; break ;;
        *) echo "Error: unsupported option $1." ; exit 1 ;;
    esac
done

STATE_PATH=${1:-""}
EXTRA=${2:-""}

if [ -z "$STATE_PATH" -o -n "$EXTRA" ]; then
    show_options 1
fi

mkdir -p /var/lib/use-ephemeral
echo $STATE_PATH >> /var/lib/use-ephemeral/stateful-paths
if [ -e "$STATE_PATH" -o -L "$STATE_PATH" ]; then
    backup_dir=/var/lib/use-ephemeral/$(dirname "$STATE_PATH")
    mkdir -p "$backup_dir"
    mv "$STATE_PATH" "$backup_dir"
fi
if [ -n "$LEAVE_SYMLINK" ]; then
    ln -s "/mnt/state/$STATE_PATH" "$STATE_PATH"
fi
