#! /bin/ksh
USAGE='USAGE: check_one_link FILE_PATH MOUNT_PATH MAP_TO_PATH
   Check one link file.  It is only allowed to be a link to below
   MOUNT_PATH if it is a link to the corresponding file and the
   corresponding file is not a link.  Otherwise, replace the 
   link with the mirror link, i.e. replace MOUNT_PATH with MAP_TO_PATH.
'
# (C) Copyright 1995 by Michael Coulter.  All rights reserved.

# Set variables

# Process parameters

   if [ $# -ne 3 ]
   then
      echo "$USAGE" >&2
      echo "Wrong number of arguments." >&2
      exit 1
   fi
   FILE_PATH="$1"; shift
   if [ ! -L "$FILE_PATH" ]
   then
      echo "$USAGE" >&2
      echo "$FILE_PATH is not a link." >&2
      exit 1
   fi
   MOUNT_PATH="$1"; shift
   if [ ! -d "$MOUNT_PATH" ]
   then
      echo "$USAGE" >&2
      echo "$MOUNT_PATH is not a directory." >&2
      exit 1
   fi
   MAP_TO_PATH="$1"; shift
   if [ ! -d "$MAP_TO_PATH" ]
   then
      echo "$USAGE" >&2
      echo "$MAP_TO_PATH is not a directory." >&2
      exit 1
   fi

   LINK="$(ls -l "$FILE_PATH" 2> /dev/null | cut -c56-500 | sed -e 's/^.* //')"
   if [ "$LINK" != "${LINK#$MOUNT_PATH}" ]
   then
      if [ "$MAP_TO_PATH" = "/" ]
      then
         USE_MAP_TO=""
      else
         USE_MAP_TO="$MAP_TO_PATH"
      fi
      EQUIV="${USE_MAP_TO}${LINK#$MOUNT_PATH}"
      if [ ! -L "$LINK" -a "$EQUIV" = "$FILE_PATH" ]
      then
         # A link is allowed to point at an equivalent real file
         exit 0
      fi
      if [ "$EQUIV" = "$FILE_PATH" ]
      then
	 NEW_LINK="$(ls -l "$LINK" 2> /dev/null | cut -c56-500 \
	               | sed -e 's/^.* //')"
	 if [ "$NEW_LINK" != "${NEW_LINK#$MOUNT_PATH}" ]
	 then
	    NEW_LINK="${USE_MAP_TO}${LINK#$MOUNT_PATH}"
	 fi
	 EQUIV="$NEW_LINK"
      fi
      # Replace the link with the equivalent mirror 
      echo "check_links: Replace link at $FILE_PATH with $EQUIV"
      replace_link "$FILE_PATH" "$EQUIV"
   fi
   exit 0
