#!/bin/bash

CWD=$(pwd)

NAME="dtc"
VERSION=${VERSION:-$(echo $NAME-*.tar.?z* | cut -d - -f2 | rev | cut -d . -f3- | rev)}
BUILD=${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-gnueabihf ;;
    *)    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 || exit 1
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 {} \;

# Configuration
sed -i 's/-Werror//' Makefile

# Compilation
make $NUMJOBS || exit 1
make DESTDIR=$PKG SETUP_PREFIX=$PKG/usr PREFIX=/usr LIBDIR=/usr/lib${LIBDIRSUFFIX} install

# Don't ship .la files:
rm -f $PKG/{,usr/}lib${LIBDIRSUFFIX}/*.la

# We shouldn't need the development stuff:
rm -fv $PKG/usr/lib${LIBDIRSUFFIX}/libfdt.a
rm -rf $PKG/usr/include

# 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 -fav \
  LICENSE README \
  $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