#!/bin/bash

# mtx.SlackBuild
# Package mtx for Slackware
# mozes@slackware.com
# ftp://ftp.badtux.net/pub/storage/mtx
 
# Build & version information:
VERSION=1.3.9
ARCH=${ARCH:-x86_64}
BUILD=${BUILD:-2}
PACKAGE=mtx
DISTRO=${DISTRO:-slamd64}

if [ $DISTRO = slackware ]; then
	PKGARCH=$ARCH
else
	PKGARCH=${ARCH}_${DISTRO}
fi

# Set initial variables:
CWD=$PWD
TMP=${TMP:-/tmp}
if [ ! -d $TMP ]; then
  mkdir -p $TMP
fi

# Build location:
PKG=$TMP/package-$PACKAGE
rm -rf $PKG
mkdir -p $PKG

# Extract source:
cd $TMP
rm -rf $PACKAGE-*
tar zxvvf $CWD/$PACKAGE-$VERSION.tar.gz 
cd $PACKAGE-$VERSION || exit 1

chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;
find . -perm 600 -exec chmod 644 {} \;
find . -perm 444 -exec chmod 644 {} \;
find . -perm 400 -exec chmod 644 {} \;
find . -perm 440 -exec chmod 644 {} \;
find . -perm 777 -exec chmod 755 {} \;
find . -perm 775 -exec chmod 755 {} \;
find . -perm 511 -exec chmod 755 {} \;
find . -perm 711 -exec chmod 755 {} \;
find . -perm 555 -exec chmod 755 {} \;

# Configure:
./configure \
   --prefix=/usr \
   --build=$ARCH-$DISTRO-linux \
   --host=$ARCH-$DISTRO-linux \
   --target=$ARCH-$DISTRO-linux || exit 1

# Avoid looking in the Kernel source:
sed -i 's?-I/usr/src/linux/include? ?g' Makefile

# Build:
make -j 10 || exit 1

# Install into package:
mkdir -pm755 $PKG/{install,usr/{sbin,doc/$PACKAGE-$VERSION,man/man1}}
install -m755 scsitape tapeinfo mtx loaderinfo $PKG/usr/sbin
install -m644 *.1 $PKG/usr/man/man1
gzip -9 $PKG/usr/man/man1/*

# Strip:
( cd $PKG
  find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
  find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
)

# Copy docs:
cp -fa mtx.doc CHANGES COMPATABILITY FAQ LICENSE README TODO \
       $PKG/usr/doc/$PACKAGE-$VERSION

# Install package description:
install -m644 $CWD/slack-desc $PKG/install

# Build the package:
cd $PKG
makepkg -l y -c n $TMP/$PACKAGE-$VERSION-$PKGARCH-$BUILD.tgz