#!/bin/bash

srcfile=""
destfile=""
cd_dir=""

function usage
{
    retval="$1"
    case "$retval" in
        0)
            ;;
        *)
            exec 1>&2
            ;;
    esac
    echo "Usage: $0 --src filename --dest linkname --cd-dir directory"
    echo
    echo "Create a link from 'filename' to 'linkname'".
    echo
    echo "--cd-dir is optional, and is nice for creating relative links."
    echo
    echo This program creates a symlink, but only if the
    echo symlink is not already present and correct.
    echo This cuts down on unnecessary sudoing.
    exit "$retval"
}

while [ "$#" -ge 2 ]
do
    case "$1" in
        --src)
            srcfile="$2"
            shift
            ;;
        --dest)
            destfile="$2"
            shift
            ;;
        --cd-dir)
            cd_dir="$2"
            shift
            ;;
        -h|--help)
            usage 0
            ;;
        *)
            echo "$0: Unrecognized option: $1" 1>&2
            usage 1
            ;;
    esac
    shift
done

case "$srcfile" in
    "")
        echo --src is a required option 1>&2
        usage 1
        ;;
esac

case "$destfile" in
    "")
        echo --dest is a required option 1>&2
        usage 1
        ;;
esac

if [ "$cd_dir" != "" ]
then
    cd "$cd_dir"
fi

function extent
{
    [ -e "$destfile" ]
}

function correct
{
    # $ stat --format %N /usr/local/bin/deep-ssh
    # below cmd output started 2018 Fri Mar 09 12:27:48 PM PST
    # '/usr/local/bin/deep-ssh' -> '../lib/deep_ssh.py'
    current_link_target=$(set -eu; set -o pipefail; readlink "$destfile")
    [ "$current_link_target" = "$srcfile" ]
}

if extent && correct
then
    exit 0
fi

# Try to remove the file/link "as me".  That we do not use -r, so a directory hierarchy will cause this to fail.
# The benefit is that we're less likely to remove something important accidentally.
if ! rm -f "$destfile" > /dev/null 2>&1
then
    sudo rm -f "$destfile"
fi

# Try to create the link "as me"
if ! ln -sf "$srcfile" "$destfile" > /dev/null 2>&1
then
    # if that fails, try to create it as root
    sudo ln -sf "$srcfile" "$destfile"
fi