#!/bin/sh

silent=0
if [ _"$1" = "_-s" ] ; then
  silent=1
  shift 1
fi

if [ $# -ne 2 ] ; then
  echo usage: `basename $0` '[ -s ] <symlink> <increment>' >&2
  exit 1
fi

c=`ls -ld $1|cut -c1`
if [ _"$c" != "_l" ] ; then
  if [ $silent -eq 0 ] ; then
    echo "Error: $1 is not a symbolic link." >&2
  fi
  exit 2
fi

AWK=""
# the solaris awk is doin' dawn f...... BS
for awk in nawk gawk awk ; do
  for dir in `echo $PATH|tr : " "` ; do
    if [ -x $dir/$awk ] ; then
      AWK=$dir/$awk
      break
    fi
  done
  if [ _$AWK != _ ] ; then
    break
  fi
done

if [ _$AWK = _ ] ; then
  if [ $silent -eq 0 ] ; then
    echo 'No awk ? Is this really a lovely UNIX ?' >&2
    echo 'Sorry. I have to exit.' >&2
  fi
  exit 1
fi

points_to=`/bin/ls -l $1|$AWK '{print $NF}'`
trailing_num=`echo $points_to|$AWK '{p=match($0,"[0-9]+$");if(p<1)print 0;else print substr($0,p)}'`
base=`echo $points_to|$AWK '{p=match($NF,"[0-9]+$");if(p<1)print $0;else print substr($0,1,p-1)}'`

new_num=`expr $trailing_num + $2`

if [ ! -f "$base""$new_num" ] ; then
  if [ $silent -eq 0 ] ; then
    echo Error: Linked file does not exist. >&2
  fi
  exit 2
fi

/bin/rm -f $1
ln -s "$base""$new_num" $1
EST=$?

if [ $EST -ne 0 ] ; then
  if [ $silent -ne 1 ] ; then
    echo "Error: Cannot create link." >&2
  fi
  exit $EST
fi

if [ $silent -eq 0 ] ; then
  echo "$base""$new_num"
fi

exit $EST
