#!/bin/bash
CWD=$(pwd)

NAME="mtd-utils"
VERSION=${VERSION:-$(echo $NAME-*.tar.?z* | cut -d - -f3 | rev | cut -d . -f3- | rev)}
BUILD="1"

NUMJOBS=${NUMJOBS:-" -j$(grep -c ^processor /proc/cpuinfo 2>/dev/null) "}


# Automatically determine the architecture we're building on:
MARCH=$( uname -m )
if [ -z "$ARCH" ]; then
  case "$MARCH" in
    i?86)    export ARCH=i586 ;;
    armv7hl) export ARCH=$MARCH ;;
    arm*)    export ARCH=arm ;;
    # Unless $ARCH is already set, use uname -m for all other archs:
    *)       export ARCH=$MARCH ;;
  esac
fi

if [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O3 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O3 -fPIC"
  LIBDIRSUFFIX="64"
elif [ "$ARCH" = "armv7hl" ]; then
  SLKCFLAGS="-O3 -march=armv7-a -mfpu=vfpv3-d16"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "arm" ]; then
  SLKCFLAGS="-O3 -march=armv7-a -mtune=cortex-a7 -mfpu=neon-vfpv4 -mfloat-abi=hard"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "aarch64" ]; then
  SLKCFLAGS="-O3 -fPIC"
  LIBDIRSUFFIX="64"
elif [ "$ARCH" = "riscv64" ]; then
  SLKCFLAGS="-O3 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

case "$ARCH" in
    arm*) TARGET=$ARCH-slackware-linux-gnueabi ;;
    *)    TARGET=$ARCH-slackware-linux ;;
esac

# Establishment tmp directory for
TMP=${TMP:-/tmp}
PKG=$TMP/package-$NAME
rm -rf $PKG
mkdir -p $PKG

# Delete a directory previous build / create new and change rights
cd /tmp
rm -rf $NAME-$VERSION
tar xvf $CWD/$NAME-$VERSION.tar.?z* || exit 1
cd $NAME-$VERSION
chown -R root:root .
find . \
 \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 555 -o -perm 511 \) \
 -exec chmod 755 {} \; -o \
 \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) \
 -exec chmod 644 {} \;

if [ ! -f configure ];then
    NOCONFIGURE=1 ./autogen.sh &>/dev/null
fi

# Configuration
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
  --prefix=/usr \
  --mandir=/usr/man \
  --infodir=/usr/info \
  --docdir=/usr/doc/$PKGNAM-$VERSION \
  --build=$TARGET

# Compilation
make $NUMJOBS || exit 1
make install DESTDIR=$PKG MANDIR=/usr/man

# Strip binaries:
find $PKG | xargs file | grep -e "executable" -e "shared object" \
  | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null

# Compress manual pages:
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

# Copy docs
mkdir -vpm755 $PKG/usr/doc/$NAME-$VERSION
cp -a COPYING \
    $PKG/usr/doc/$NAME-$VERSION/

# Description and installation script
mkdir -p $PKG/install
zcat $CWD/doinst.sh.gz > $PKG/install/doinst.sh
cat $CWD/slack-desc > $PKG/install/slack-desc

# Package creation
cd $PKG
makepkg -l n -c n $TMP/${NAME}-${VERSION}-${ARCH}-${BUILD}.txz
