#!/bin/sh
# symlinks ---
#
# This script is used to install symbolic links.  The information is read
# from a external file.  The format of the file is as follows.  Each line
# is interpreted to be a record containing two fields separated by a :
# the first field is the name of the symbolic link to create.  The second
# record is what gets pointed to.
#

# initialize variables
link_file="SYMLINKS.LIST"
os_uname=`uname`
cd_dir="."

USAGE='symlinks [-f link_file] [-C dir]
-f - the name of the file to read data from (default: '$link_file')
-C - change to this directory before installing the links.  Good for
     installing relative links. (default: .)'


# initialize variables

# check to see what options for test is for symbolic links
# gnu's test uses -L for sym links.  the regular test uses -h
# testvar=`test -h .  > /dev/null 2>&1`
#if [ $? -ne "0" ]
if test -h .
then
   testl="-L"
else
   testl="-h"
fi


# parse command line options

while getopts hf:C: opt
do
   case $opt in
   h| ?)        echo "$USAGE"
                exit 1;;
   f)           link_file=$OPTARG;;
   C)           cd_dir=$OPTARG;;
   esac
done
#shift `expr $OPTIND - 1`

# ---------- begin body --------

# read in the list to a variable
if [ -f "$link_file" -a -s "$link_file" ]
then
    list=`cat $link_file`
else
    os_link_file=$link_file.$os_uname
    if [ -f "$os_link_file" -a -s "$os_link_file" ]
    then
	echo "Using $os_link_file"
	list=`cat $os_link_file`
    else
	echo "Data file: $link_file not found" 1>&2
	exit 1
    fi
fi

# change to the desired directory
cd "$cd_dir"

# now loop over the list of records
for record in $list
do
   # parse out the fields
   link_name=`echo $record | cut -d: -f1`
   link_dest=`echo $record | cut -d: -f2`

   # check fpor the existence of the link
   if [ "$testl" "$link_name" ]
   then
      rm "$link_name"
   elif [ -f "$link_name" ]
   then
      # hey its there but not a link
      echo "File: $link_name already exits as a file not a link" 1>&2
      continue    # skip to next name in list
   fi

   # add the link
   if [ ! -d "`dirname $link_name`" ]
   then
     echo "make directory `dirname $link_name`"
     mkdir -p `dirname $link_name`
   fi
   echo "adding link $link_name to $link_dest"
   ln -s "$link_dest" "$link_name"

done

exit 0
