#!/bin/bash

# This SlackBuild builds the master branch of hostnamed.


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

PRGNAM=hostnamed
VERSION=${VERSION:-2026_master.3}
BUILD=${BUILD:-1}
TAG=${TAG:-_FRG}
PKGTYPE=${PKGTYPE:-txz}

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/FORGE}
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 $TMP
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
cp -R $CWD/* .

chown -R root:root .
find . -type f \( -perm -4000 -o -perm -2000 \) -exec chmod -s {} +
find . ! -type l -type d ! -perm 755 -exec chmod -f 755 {} +
find . ! -type l -type f -perm /111 ! -perm 755 -exec chmod -f 755 {} +
find . ! -type l -type f ! -perm /111 ! -perm 644 -exec chmod -f 644 {} +

export CFLAGS="$SLKCFLAGS"
export CXXFLAGS="$SLKCFLAGS"
mkdir meson-build
cd meson-build
meson setup \
  --prefix=/usr \
  --libdir=lib${LIBDIRSUFFIX} \
  --libexecdir=/usr/libexec \
  --bindir=/usr/bin \
  --sbindir=/usr/sbin \
  --includedir=/usr/include \
  --datadir=/usr/share \
  --sysconfdir=/etc \
  --localstatedir=/var \
  --mandir=/usr/man \
  --buildtype=release \
  -Dprivileged-group=wheel \
  -Dhostname_conf=/etc/HOSTNAME \
  -Dmachine_conf=/etc/machine-info \
  -Dos_conf=/etc/os-release \
  .. || exit 1
  "${NINJA:=ninja}" $NUMJOBS || exit 1
  DESTDIR=$PKG $NINJA install || exit 1
cd ..

# Slackware bash client (analogous to timedatectl). hostnamed picks up the
# file changes via inotify and refreshes its D-Bus properties.
mkdir -p $PKG/usr/bin
cat slack/hostnamectl > $PKG/usr/bin/hostnamectl
chmod 755 $PKG/usr/bin/hostnamectl

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

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

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp -a README.md AUTHORS BUG-NEWS NEWS COPYING $PKG/usr/doc/$PRGNAM-$VERSION 2>/dev/null || true
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-"$VERSION"/$PRGNAM.SlackBuild

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

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