#!/bin/bash

# Slackware build script for iodine

# Written by David Miller.
# This script is released into the public domain.
# Modified and now maintained by B. Watson <urchlay@slackware.uk>.
# If you live in a country where public domain isn't valid,
# you can consider this to be licensed under the WTFPL. See
# http://www.wtfpl.net/txt/copying/ for details.

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

PRGNAM=iodine
VERSION=${VERSION:-0.9.0}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}

SRCVERSION=$(echo $VERSION |tr _ -)

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" -o "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=$ARCH -mtune=i686"
elif [ "$ARCH" = "x86_64" -o "$ARCH" = "aarch64" ]; then
  SLKCFLAGS="-O2 -fPIC"
else
  SLKCFLAGS="-O2"
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$SRCVERSION
tar xvf $CWD/$PRGNAM-$SRCVERSION.tar.gz --no-same-owner
cd $PRGNAM-$SRCVERSION
find . ! -type l    -a \( \
  \(     -perm /111 -a ! -perm 755 -a -exec chmod -f 755 {} + \) -o \
  \(   ! -perm /111 -a ! -perm 644 -a -exec chmod -f 644 {} + \) \)

sed -i 's,README,README.md,g' man/*.8.in

# 20261027 bkw: upstream using meson as of 0.9.0.
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
meson setup \
  --buildtype=release \
  --infodir=/usr/info \
  --libdir=/usr/lib${LIBDIRSUFFIX} \
  --localstatedir=/var \
  --mandir=/usr/man \
  --prefix=/usr \
  --sysconfdir=/etc \
  -Dstrip=true \
  build/
"${NINJA:=ninja}" -vC build/
DESTDIR=$PKG $NINJA -vC build/ install

gzip -9 $PKG/usr/man/man*/*
rm -rf $PKG/usr/share # nothing here but doc/

PKGDOC=$PKG/usr/doc/$PRGNAM-$VERSION
mkdir -p $PKGDOC
cp -a CHANGELOG README.md LICENSE doc/* $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
