#!/bin/bash

# Slackware build script for TriliumNotes

# Copyright 2026  Bruno Russo (brusso@gmail.com) Sao Paulo,SP BR
# 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=TriliumNotes
VERSION=${VERSION:-0.106.0}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}
OUTPUT=${OUTPUT:-/tmp}
TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
ARCH='x86_64'
SRCARCH='x64'

set -e

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

rm -rf $PKG
mkdir -p "$TMP" "$PKG" "$OUTPUT"

cd "$PKG"
rpm2cpio "$CWD/${PRGNAM}-v${VERSION}-linux-${SRCARCH}.rpm" | cpio -idmv
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
find $PKG -print0 | xargs -0 file | grep -e "executable" -e "shared object" | grep ELF \
  | cut -f 1 -d : | xargs chmod 0755 2> /dev/null || true

mv $PKG/usr/lib $PKG/usr/lib64
rm -f $PKG/usr/bin/trilium
cat > $PKG/usr/bin/trilium << EOF
#!/bin/bash
exec /usr/lib64/trilium/trilium "\$@"
EOF
chmod 0755 $PKG/usr/bin/trilium

rm -rf $PKG/usr/lib64/.build-id

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild
install -m0644 $PKG/usr/share/doc/trilium/copyright $PKG/usr/doc/$PRGNAM-$VERSION/
rm -rf $PKG/usr/share/doc

mkdir -p "$PKG/install"
install -m 0644 "$CWD/slack-desc" "$PKG/install/slack-desc"
[ -r "$CWD/doinst.sh" ] && install -m 0644 "$CWD/doinst.sh" "$PKG/install/doinst.sh"

chown -R root:root "$PKG/"
find "$PKG/" -type d -exec chmod 755 {} \;
[ -d "$PKG/usr/share/applications" ] && chmod 644 "$PKG/usr/share/applications"/*.desktop || true
[ -d "$PKG/usr/share/pixmaps" ] && find "$PKG/usr/share/pixmaps" -type f -exec chmod 644 {} \;

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