#! /bin/bash
# (c) by ennit interactive GmbH, 2018
# Author jbradler@ennit.de

if [ "$(id -u)" != "0" ]; then
    echo "Script $0 must be run as user root." 1>&2
    echo "Aborting."
    exit 1
fi

if [[ $# -ne 2 ]] ; then
    echo "Missing arguments."
    echo "Usage: $0 {symlinkSource} {symlinkTarget}"
    echo "Aborting."
    exit 1
fi

SOURCE=$1
TARGET=$2

if [ ! -f "${SOURCE}" ] && [ ! -d "${SOURCE}" ]; then
    echo "Source for symlink does not exist."
    echo "Aborting."
    exit 1
fi

if [ ! -d $( dirname "${TARGET}") ]; then
    echo "Creating directory $( dirname ${TARGET})"
    mkdir -p $( dirname "${TARGET}")
fi

if [ -L "${TARGET}" ]; then
    check_source=`readlink -f "${TARGET}"`
	if [ "${check_source}" != "${SOURCE}" ]; then
	    # renew symlink
	    rm -f "${TARGET}"
	    ln -s "${SOURCE}" "${TARGET}"
		if [ $? -ne 0 ]; then
			echo ">>> ERROR: Could not set symlink"
			echo "${TARGET} --> symlinks to --> ${SOURCE}"
			exit 1
		fi
	elif [ "${check_source}" == "${SOURCE}" ]; then
	    # symlink is fine
		echo ">>> OK: Symlink already set"
		echo "${TARGET} --> symlinks to --> ${SOURCE}"
	fi
	exit 0
elif [ -f "${TARGET}" ]; then
	echo ">>> ERROR: Could not set symlink. File exists already and is not a symlink."
	echo "${TARGET} --> symlinks to --> ${SOURCE}"
	exit 1
fi

# set new symlink
ln -s "${SOURCE}" "${TARGET}"
if [ $? -ne 0 ]; then
	echo ">>> ERROR: Could not set symlink"
	echo "${TARGET} --> symlinks to --> ${SOURCE}"
	exit 1
else
	echo ">>> OK: Symlink set"
	echo "${TARGET} --> symlinks to --> ${SOURCE}"
fi