#!/bin/bash -

# H.A.Trujillo
# 26 Jun 2014
# Last Change:     29 Jul 2017
# Version:	   1.3.5a

case _$1 in 
  _-h|_--help|_)

    ul=$'\e[4m'
    pl=$'\e[m'
    cat <<- EOH

	     usage:	${0##/*/}  file  [path]

	  Places a relative symbolic link to ${ul}file$pl at ${ul}path${pl}.

	  ${ul}path${pl} may be a file or a directory.  If no path is
	  specified, the symlink is placed in the current directory.

	  Caveat:  This script dies ungracefully if any internal component of
	           the target and link paths match.
	           (eg:  a/b/XYZ/c/foo --> p/q/XYZ/r/foo)

	EOH
	exit
    ;;

  _/*)
    ;;

  _*) 
     cd -P  $(dirname $1)
     foo=( "`pwd -P`/`basename $1`" "$2" )
     set ${foo[@]}
     cd -
    ;;
  esac

if [ $# == 2 ] ; then
    if [ -d $2 ] 
    then 
	cd -P $2 || exit 1
	destdir=$2
	newname=""
    else 
	destdir=`dirname  "$2"`
	newname=`basename "$2"`
	cd -P $destdir || exit 1
    fi
fi

if ! test -e  "$1" ; then
    echo "${0##/*/}: source  $1  does not exist"
    exit 1
fi

echo $1 | awk -v newname="$newname" \
	      -f <( sed -e '1,/^#---end-of-wrapper-script---/d' $0 )
exit

#---end-of-wrapper-script---

#!/usr/bin/awk -f
BEGIN{
  FS="/"
  q="\x22"	# quotation mark for output to shell
  "pwd -P" | getline rawPWD
  pwd_max=split(rawPWD, pwd)
}

{
  file_max=split($0,file)

  n=0
  while ( n < pwd_max ) {
    n++
    if ( pwd[n] == file[n] ) {
      file[n] = ""
    } else {
      path = path "../"
    }
  }

  n=1
  while (n < file_max) {
    n++
    path = path FS file[n] 
  }

  gsub("/{2,}", "/", path)
  sub ("^/", "", path)
  sub ("/$", "", path)

  linkname = path
  if ( newname != "" ) {
      gsub("[^/]*$", newname , linkname) 
      newname=q newname q	# must do here to prevent quoting of null value
  }
  print "\n     creating link " linkname"\n                in " rawPWD

  print "ln -s " q path q, newname | "sh"
  if ( newname == "" ) { newname = file[file_max] }
  if ( newname == "" ) { newname = file[file_max-1] }
  print "touch -h -r " q path q " " newname | "sh" 

}

#  Changes:
# 	26 nov 14	Date of symlink now matches that of the target
# 	09 Jan 15	Symlink-date now can deal with /tmp being a
# 			link to /private/tmp
#	27 Apr 15	Can specify a new name for the link
#	11 Jun 15	User-message now reflects new name, if new name given
#	10 Aug 16	can now specify a directory target as "foo/bar/"
#			as well as "foo/bar"
#	24 May 17	Can now handle spaces in file/directory names
#	12 Jul 17	pwd and cd now all use -P flag
#
