#!/bin/bash

# Slackware build script for coppwr

# Copyright 2025-2026  fourtysixandtwo <fourtysixandtwo@sliderr.net>
# Copyright Ioannis Anagnostakis 2025
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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

PRGNAM=coppwr
VERSION=${VERSION:-1.7.1}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}
VSBUILD=${VSBUILD:-1}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i686 ;;
    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" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
elif [ "$ARCH" = "aarch64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

if [ "$ARCH" = "arm" ]; then
  TRIPLET="$ARCH-unknown-linux-gnueabihf"
else
  TRIPLET="$ARCH-unknown-linux-gnu"
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-$VERSION-*.tar.?z
cd $PRGNAM-$VERSION
chown -R root:root .
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 {} + \)

# prevent cargo from using the network.
# this only works because we have a vendored sources tarball with
# everything cargo would have downloaded.
export CARGO_NET_OFFLINE=true

# prevent cargo from writing outside of $TMP
export CARGO_HOME=$(pwd)/.cargo

export PATH="/opt/rust/bin:$PATH"
if [ -z "$LD_LIBRARY_PATH" ]; then
  export LD_LIBRARY_PATH="/opt/rust/lib$LIBDIRSUFFIX"
else
  export LD_LIBRARY_PATH="/opt/rust/lib$LIBDIRSUFFIX:$LD_LIBRARY_PATH"
fi

### start of section to build with stock pipewire on 15.0
# Detect pipewire version to continue patching for stock slackware-15.0 pipewire...
PWVERSION=$(cd /var/log/packages/ ; ls pipewire-* | cut -d- -f2 )

if [ "$PWVERSION" = "0.3.44" ]; then
# Patch libspa for compatibility with older PipeWire (Slackware 15.0)
  echo "Patching libspa for older PipeWire compatibility"
  echo "Upgrade to pipewire in 15.0 testing to skip this mess as noted in the README"

# Note: We use grep -v to exclude libspa-sys because the file we need to patch
  # (src/param/video/raw.rs) exists in libspa, not libspa-sys. The find command
  # can return directories in different orders depending on filesystem/environment,
  # so we explicitly filter to get the correct crate.
# Following echo debug outputs to verify we found the correct directory structure in github sbo-bot container.
# (can be removed once confirmed building in all environments or in first pkg update)
# https://github.com/SlackBuildsOrg/slackbuilds/pull/12831
  LIBSPA_DIR=$(find vendor -maxdepth 1 -name "libspa*" -type d | grep -v "libspa-sys" | head -1)
  echo "DEBUG: LIBSPA_DIR (without sys) = $LIBSPA_DIR"

  if [ -n "$LIBSPA_DIR" ]; then
    echo "DEBUG: Checking for raw.rs in libspa:"
    ls -la "$LIBSPA_DIR/src/param/video/raw.rs" 2>/dev/null || echo "Not found in libspa"

    LIBSPA_RAW="$LIBSPA_DIR/src/param/video/raw.rs"

    if [ -f "$LIBSPA_RAW" ]; then
      echo "DEBUG: Found! Patching $LIBSPA_RAW"
      sed -i '/^[[:space:]]*flags: 0,$/d' "$LIBSPA_RAW"
      sed -i 's/self\.0\.flags = flags\.bits();/\/\/ self.0.flags = flags.bits(); \/\/ removed for older PipeWire/' "$LIBSPA_RAW"
      sed -i 's/VideoFlags::from_bits_retain(self\.0\.flags)/VideoFlags::empty() \/\/ flags removed for older PipeWire/' "$LIBSPA_RAW"
      sed -i 's/self\.0\.modifier = modifier;/self.0.modifier = modifier as i64;/' "$LIBSPA_RAW"
      sed -i 's/^\([[:space:]]*\)self\.0\.modifier$/\1self.0.modifier as u64/' "$LIBSPA_RAW"
      # this is a hacky way to fix the checksum after the above patching
      sed -i 's/0e811fe30ca3d9d887b95ab4ee56591b70ce73cf445e43a2992e25cddb4d07fe/962841ea7ae0aa61f9a5200bbd9f025ba46fec9481f2e63c7eae248ef3e1ca5b/' vendor/libspa/.cargo-checksum.json
    else
      echo "ERROR: Could not find raw.rs file to patch!"
    fi
  fi
else
  echo ""
fi
### end of section to build with stock pipewire on 15.0

CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
cargo build --offline --release --target $TRIPLET

mkdir -p $PKG/usr/bin
install -m 755 target/$TRIPLET/release/$PRGNAM $PKG/usr/bin/
install -Dm644 "assets/io.github.dimtpap.coppwr.desktop" "$PKG/usr/share/applications/io.github.dimtpap.coppwr.desktop"
install -Dm644 "assets/io.github.dimtpap.coppwr.metainfo.xml" "$PKG/usr/share/metainfo/io.github.dimtpap.coppwr.metainfo.xml"
install -Dm644 "assets/icon/scalable.svg" "$PKG/usr/share/icons/hicolor/scalable/apps/io.github.dimtpap.coppwr.svg"
install -Dm644 "assets/icon/512.png" "$PKG/usr/share/icons/hicolor/512x512/apps/io.github.dimtpap.coppwr.png"
install -Dm644 "assets/icon/256.png" "$PKG/usr/share/icons/hicolor/256x256/apps/io.github.dimtpap.coppwr.png"
install -Dm644 "assets/icon/128.png" "$PKG/usr/share/icons/hicolor/128x128/apps/io.github.dimtpap.coppwr.png"
install -Dm644 "assets/icon/64.png" "$PKG/usr/share/icons/hicolor/64x64/apps/io.github.dimtpap.coppwr.png"
install -Dm644 "assets/icon/48.png" "$PKG/usr/share/icons/hicolor/48x48/apps/io.github.dimtpap.coppwr.png"
install -Dm644 "assets/icon/32.png" "$PKG/usr/share/icons/hicolor/32x32/apps/io.github.dimtpap.coppwr.png"

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

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp -a LICENSE README.md $PKG/usr/doc/$PRGNAM-$VERSION
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

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

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