#!/bin/sh
#
#       $Id: //depot2/idl/Installers/idl-unix-scripts/trunk/src/make_link#3 $
#
# make_link
#
# This script places a symbolic link named $2 to existing file $1.
#       $1 - The target file or directory.
#       $2 - The link name
#       $3 - Not Interactive  1=NOT_INTERACTIVE
#
# Note: Some versions of Unix test use -h for symlinks, others use -L, and
#       some lack the ability altogether. This means that we have to limit
#       ourselves to the basic codes (r, w, d) which don't go far enough.
#	However, all systems have /bin/ls...
#


if [ \(  -f /bin/dirname \) -o \(  -f /usr/bin/dirname \) ]; then
   UDIR=`dirname $0`
else
   UDIR=`echo $0 | awk -F\/ '{if(NF==1)
   printf(".\n");else{for(i=1;i<NF;i++){if(i>1)printf("%s","/"); printf("%s",$i);}printf("\n")}}'`
fi
echo " "


if [ "$3" = "1" ]; then
   INTERACTIVE=0	
else
   INTERACTIVE=1
fi
#### LINKDIR=`dirname $2`
LINKDIR=`echo $2 | sed 's?/[^/]*$??'`
LINK_DONE=0
if [ "`/bin/ls -1 $1 2> /dev/null`" = "" ]; then
    echo "    Warning: Target file does not exist:
        $1
"
fi

if [ ! -d $LINKDIR ]; then
    echo "    Unable to create symbolic link:
        $LINKDIR does not exist."
    exit 1
fi
if [ ! -w $LINKDIR ]; then
    echo "    Unable to create symbolic link:
        $LINKDIR is not writable."
    exit 1
fi

# If its already there, and is a directory, assume all is OK:
if [ -d $2 ]; then 
        echo "    Directory " $2 " already exists --- No link is needed."
        exit 0
fi

if [ "`/bin/ls -1 $2 2> /dev/null`" != "" ]; then
  cmp $1 $2 > /dev/null 2>&1
  if [ "$?" = "0" ]; then               # Already there and the same? OK...
      LINK_DONE="1"
  else
    if [ $INTERACTIVE = "0" ]; then
       echo "Removing existing link "
       rm -f $2;
    else
       echo "    Link Name: $2
       Points at: $1
       A file with the same name as the desired symbolic link
         already exists and is different from the pointed at file."
       if [ `sh $UDIR/yesno "Remove link file to make new link possible"` = 0 ]
       then
         echo "    Link aborted."
         exit 1;
       fi
       echo " "
       rm -f $2;
    fi
  fi
fi

if [ "$LINK_DONE" = 0 ]; then
  ln -s $1 $2 > /dev/null 2>&1
  if [ "`/bin/ls -1 $2 2> /dev/null`" = "" ]; then
    echo "    Unable to create symbolic link:
        $2"
    exit 1
  fi
fi

echo "    Link Name: $2
    Points at: $1"

exit 0
