#!/bin/bash

# echo "$0 args: " "$@"

[[ -z "$4" ]] && { echo "use: $0 target alias-base alias-path id" ; exit 2; }
[[ -d $1 ]] || { echo "$1: not a directory" ; exit 1 ; }

cd $2 || exit $?

# see if it is already there
[[ -L $3 ]] && [[ $1 -ef $3 ]] && exit 0

# echo "updating..." >&2 #dbg

ap=$3
id=$4

# clean old link
if [[ -f .alias_clean$id ]] ; then
   t=`cat .alias_clean$id`
   # echo "cleaning $t" #dbg
   rm -f $t
   p=${t%/*}
   [[ "$p" != "$t" ]] && rmdir -p $p
fi
# [[ -L $3 ]] && rm -f $3

# remove old dir (this will happen only on the 1st run)
if [[ -d $ap ]] ; then
   rmdir -p $ap || exit $?
fi


# create new link (and parent dir, if needed)
p=${ap%/*}
if [[ "$p" != "$3" ]] ; then
   # echo "creating dir $p" >&2 #debug
   mkdir -p $p || exit $?
fi

ln -s $1 $3

# update cleanup info
echo $ap >.alias_clean$id

