#!/bin/sh
# trying to get pkgname from a full package name
# this will work for something like
# aaa-1-i386-1.tgz
# aaa-1.2-i386-1.tgz
# aaa-1.2-patched-i386-1.tgz
# aaa-bbb-1.2-i386-1.tgz
# aaa-bbb-100dpi-1.2-i386-1.tgz
# aaa-bbb-20000101-i386-1.tgz
# aaa-bbb-2000_01_01-i386-1.tgz
# aaa-IIIbeta2-i386-1.tgz
#
# BUT BROKEN for this (in this case, put them in KNOWN_NAMES list)
# aaa-IIIbeta2-gtk1-i386-1.tgz
#
# (c) 2004, Eko M. Budi
# License: GNU GPL

if [ -z "$1" ]; then
cat << _EOF_
pkgname - return the name portion of a Slackware package.
Usage: pkgname <full_package_name>

Example:
pkgname aaa-bbb-1.2.3-i486-1.tgz
_EOF_
exit 1
fi

# put guys with strange VERSION here
KNOWN_NAMES="cdparanoia libjpeg slib"
# Add more archs here, if you know
KNOWN_ARCHS="noarch i386 i486 i586 i686 i786 i886 i986 x86_64"

pkgname1() {
name=${1%%-*}
ver_rest=${1#$name-}
while [ 0 ]; do
   ## 1st rule, if known name then that's it !
   if echo " $KNOWN_NAMES " | grep -q " $name "; then
       break
   fi
   ## 2nd rule, if digits followed by . - or _ then stop
   if echo $ver_rest | grep -qe "^[0-9]*[\.\-\_]"; then
      break
   fi
   ## 3rd, if the next segment is known architecture, stop
   extra=${ver_rest%%-*}
   ver_rest=${ver_rest#$extra-}
   if echo "$KNOWN_ARCHS " | grep -q `echo $ver_rest | cut -f1 -d-`; then
      break
   fi
   ## 4rd, no more rest, then break
   if [ "$ver_rest" = "$extra" ]; then
      break
   fi
   ## concat the name then continue
   name="${name}-${extra}"
done
echo $name
}

# Return package name, from Jason Woodward
# This is faster than the ortodox way,
# but DOES NOT WORK if the package does not follow convention
# notably VERSION with -, e.g:
# xine-lib-1.0-rc1-i486-1 --> return xine-lib-1.0
# In that case, the culprit should be renamed, 
# replace '1.0-rc1' with '1.0_rc1'. 
pkgname2() {
    echo $1 | sed -re "s/(.*{1,})\\-(.*[\\.\\-].*[\\.\\-].*)[ ]{0,}$/\1/"
}

# The world is not always perfect, so let's use the ortodox way, ok ?
pkgname1 $1
