#!/bin/sh
# Copyright 2023 Kurt Nienhaus

if test "$1" = "" || test "$2" = ""
then
  echo "usage: $0 [<path>/]<library> <installation path>" >&2
  echo "(e.g.: $0 libmonkey.so.1.2p0 /usr/local/lib)" >&2
  exit 1
fi

library="$1"
instpath="`echo $2 | sed -e 's%/*$%%'`"

test -d $instpath || { echo "$0: error: \"$instpath\" is no directory" >&2; exit 1; }

# copy library
rm -f $instpath/$library
cp $library $instpath/ && chmod 755 $instpath/`basename $library` || exit 1


# +++ delete old libraries and create links +++

dateipatch="`basename $library`"
dateiminor="`echo $dateipatch | sed -e 's/\.\([0-9]*\)p[^.]*$/.\1/'`"
dateimajor="`echo $dateiminor | sed -e 's/\.[^.]*$//'`"
datei="`echo $dateimajor | sed -e 's/\.[^.]*$//'`"

cd $instpath || exit 1

# create links
rm -f $dateimajor
ln -s $dateipatch $dateimajor
rm -f $datei
ln -s $dateimajor $datei

# delete old libraries
patchnr="`echo $dateipatch | sed -e 's/.*\.[0-9]*//' -e 's/p//'`"
if test "$patchnr" != "" && test $patchnr -gt 0
then
  rm -f $dateiminor
  nr=1
  while test $nr -lt $patchnr
  do
    rm -f ${dateiminor}p$nr
    nr=`expr $nr + 1`
  done
fi

exit 0
