#!/bin/bash
# Slackware build script for <zita-alsa-pcmi>
# Written by Michales Michaloudes korgie@gmail.com <2014>

# 20250207 bkw: modified by SlackBuilds.org, BUILD=2.
# These modifications were made with permission from the maintainer.
# - install apps in /usr/bin.
# - actually use SLKCFLAGS consistently.
# - de-uglify the build/install process. easier to read now.

cd $(dirname $0) ; CWD=$(pwd)

PRGNAM=zita-alsa-pcmi
VERSION=${VERSION:-0.6.1}
BUILD=${BUILD:-2}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$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"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-$VERSION.tar.bz2
cd $PRGNAM-$VERSION
chown -R root:root .
find -L .  -perm /111 -a \! -perm 755 -a -exec chmod 755 {} + -o \
        \! -perm /111 -a \! -perm 644 -a -exec chmod 644 {} +

# 20250209 bkw: DRY principle
SOLIB=lib$PRGNAM.so.$VERSION
PKGLIB=$PKG/usr/lib$LIBDIRSUFFIX

# 20250209 bkw: DRY again
build_in_dir() {
  make -C $1 \
    CXXFLAGS="$SLKCFLAGS -I$PKG/usr/include" LDFLAGS="-L$PKGLIB"
  make -C $1 install \
    DESTDIR=$PKG PREFIX=/usr SUFFIX="$LIBDIRSUFFIX"
}

# 20250209 bkw: make this dir, or the package will have a binary
# called usr/bin that *destroys* the real /usr/bin!
mkdir -p $PKG/usr/bin

# 20250209 bkw: don't let the Makefiles create a real /usr/bin
# (outside $TMP), or run ldconfig on the real root.
sed -i '/install -d/d' apps/Makefile
sed -i 's/ldconfig/& -N $(DESTDIR)$(LIBDIR)/' source/Makefile

build_in_dir source
build_in_dir apps
strip $PKG/usr/bin/* $PKGLIB/lib*.so.*.*

PKGDOC=$PKG/usr/doc/$PRGNAM-$VERSION
mkdir -p $PKGDOC
cp -a AUTHORS COPYING README $PKGDOC
cat $CWD/$PRGNAM.SlackBuild > $PKGDOC/$PRGNAM.SlackBuild

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE
