#!/bin/bash -x
set -e
function gen-conf () {
CONFDIR="$1"
DESTDIR="$2"
METHOD="$3"

    cat >"/etc/switchconf/conf" <<EOF
conf_top_dirs="$CONFDIR"
dest_dir="$DESTDIR"
config_method="$METHOD"
EOF
}

CONFDIR=`mktemp -d /tmp/switchconf-confdir-XXXXXX`
DESTDIR=`mktemp -d /tmp/switchconf-destdir-XXXXXX`
TMPFILE=`mktemp`
rm $TMPFILE && mv /etc/switchconf/conf $TMPFILE || true


# Setup configurations
mkdir -p "$CONFDIR/test1a"
mkdir -p "$CONFDIR/test1b"
echo test1a > "$CONFDIR/test1a/test1" 
echo test1b > "$CONFDIR/test1b/test1"

# Test switch by cp
gen-conf "$CONFDIR" "$DESTDIR" copy
if test -e "$DESTDIR/test1" ; then
    echo "Failed to setup test1"
    exit 1
fi
./switchconf test1a
if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to create file"
    exit 1
fi

if ! grep test1a "$DESTDIR/test1" ; then
    echo "Failed to put the rigth file in place"
    exit 1
fi

if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to setup test1"
    exit 1
fi
./switchconf test1a
if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to create file"
    exit 1
fi

if ! grep test1a "$DESTDIR/test1" ; then
    echo "Failed to put the rigth file in place"
    exit 1
fi

# Test switch by softlink
gen-conf "$CONFDIR" "$DESTDIR" softlink
rm -f "$DESTDIR/test1"
if test -e "$DESTDIR/test1" ; then
    echo "Failed to setup test1"
    exit 1
fi
./switchconf test1a
if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to create file"
    exit 1
fi

if ! test -L "$DESTDIR/test1" ; then
    echo "Failed to create link"
    exit 1
fi

if ! grep test1a "$DESTDIR/test1" ; then
    echo "Failed to put the rigth file in place"
    exit 1
fi

if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to setup test1"
    exit 1
fi
./switchconf test1a
if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to create file"
    exit 1
fi

if ! test -L "$DESTDIR/test1" ; then
    echo "Failed to create link"
    exit 1
fi

if ! grep test1a "$DESTDIR/test1" ; then
    echo "Failed to put the rigth file in place"
    exit 1
fi

# Test switch by hardlink
gen-conf "$CONFDIR" "$DESTDIR" hardlink
rm -f "$DESTDIR/test1"
if test -e "$DESTDIR/test1" ; then
    echo "Failed to setup test1"
    exit 1
fi
./switchconf test1a
if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to create file"
    exit 1
fi

if ! grep test1a "$DESTDIR/test1" ; then
    echo "Failed to put the rigth file in place"
    exit 1
fi

if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to setup test1"
    exit 1
fi
./switchconf test1b
if ! test -e "$DESTDIR/test1" ; then
    echo "Failed to create file"
    exit 1
fi

if ! grep test1b "$DESTDIR/test1" ; then
    echo "Failed to put the rigth file in place"
    exit 1
fi

