#!/bin/sh
# Heavily based on the Slackware64 13.1 SlackBuild
# convmv
# http://www.j3e.de/linux/convmv/
# The Italian Slackware Community
# http://www.slacky.eu/
# Packager anycolouryoulike

set -e

NAME=convmv
VERSION=1.14
ARCH=noarch
BUILD=1sl

URL=http://www.j3e.de/linux/$NAME/$NAME-$VERSION.tar.gz
SOURCE=$(basename $URL)
DOCS="CREDITS Changes GPL2 VERSION"

CWD=$(pwd)
TMP=/tmp/tgz/$NAME-$VERSION-$BUILD
PKG=$TMP/package

CHOST="i486"
if [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
  CHOST="x86_64"
fi

download_source() {
if [ ! -f $SOURCE ]; then
    wget $URL
fi
}
clean_directories() {
rm -rf $TMP
rm -rf $PKG
mkdir -p $TMP $PKG
}
explode_archive() {
tar xvf $CWD/$SOURCE
}
set_permissions() {
chown -R root:root .
chmod -R u+w,go+r-w,a-s .
}
copy_docs() {
mkdir -p $PKG/usr/doc/$NAME-$VERSION
cat $CWD/slack-desc > $PKG/usr/doc/$NAME-$VERSION/slack-desc
cat $CWD/$NAME.SlackBuild > $PKG/usr/doc/$NAME-$VERSION/$NAME.SlackBuild
for i in AUTHORS ChangeLog COPYING INSTALL LICENSE* NEWS README TODO $DOCS
do
    if [ -s $i ]; then
	cp -a $i $PKG/usr/doc/$NAME-$VERSION
    fi
done
}
strip_files() {
find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs -r strip --strip-unneeded
find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs -r strip --strip-unneeded
find . | xargs file | grep "current ar archive" | cut -f 1 -d : | xargs -r strip --strip-unneeded
if [ -d $PKG/usr/man ]; then
    find $PKG/usr/man -type f -exec gzip -9 {} \;
    for i in $(find $PKG/usr/man -type l); do ln -s $( readlink $i ).gz $i.gz; rm $i; done
fi
}
build_package() {
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
if [ -f $CWD/doinst.sh ]; then
    cat $CWD/doinst.sh > $PKG/install/doinst.sh
fi
chown -R root:root $PKG
if [ -x /usr/bin/requiredbuilder ]; then
    requiredbuilder -y -v -s $CWD $PKG
fi
makepkg -l y -c n $CWD/$NAME-$VERSION-$ARCH-$BUILD.txz
}

download_source
clean_directories
cd $TMP
explode_archive
cd $NAME*
set_permissions
make
make install PREFIX=/usr MANDIR=/usr/man DESTDIR=$PKG
copy_docs
cd $PKG
strip_files
build_package

if [ "$1" ]; then
    if [ "$1" = "--cleanup" ]; then
	rm -rf $TMP
	rm -rf $PKG
    else
	echo "$0: unrecognized option \`$1'"
    fi
fi

exit
