#!/bin/sh
#
# jabref.SlackBuild
# 2024-05-20
#
# JabRef
# is an open source bibliography reference manager.
# The native file format used by JabRef is BibTeX,
# the standard LaTeX bibliography format.

PRGNAM=jabref
VERSION=5.14

# automatically determine the architecture
if [ -z "$ARCH" ]; then
  case "$(uname -m)" in
    x86_64) ARCH=x86_64 ;;
       *) exit 1
  esac
fi

BUILD=${BUILD:-1}
TAG=${TAG:-scr}
PKGTYPE=${PKGTYPE:-txz}

HOMEPAGE="https://www.jabref.org/"
SOURCE="JabRef-${VERSION}-portable_linux.tar.gz"
DOWNLOAD="https://builds.jabref.org/main/${SOURCE}"
MD5SUM="ecf5e37481e9d548b579a924038f778e"

REQUIRES=""

MAINTAINER="Gernot Walzl"
EMAIL="gernot.walzl@gmx.at"

DESC="JabRef

is an open source bibliography reference manager.
The native file format used by JabRef is BibTeX,
the standard LaTeX bibliography format.

${HOMEPAGE}"

DOCS="$(pwd)/$0"

# EOF info


# set initial variables
CWD=$(pwd)
TMP=${TMP:-/tmp}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

# exit on error
set -e

# download the source if needed
if [ ! -f $CWD/$SOURCE ]; then
  wget -O $CWD/$SOURCE $DOWNLOAD || exit 1
fi

# check for correct source file
if [ "$(md5sum $CWD/$SOURCE | cut -f 1 -d ' ')" != "$MD5SUM" ]; then
  exit 1
fi

# extract the application source
cd $TMP || exit 1
tar xvf $CWD/$SOURCE || exit 1

# change to the application source directory
cd JabRef || exit 1

# fix permissions
chown -R root:root .
chmod -R u+w,go+r-w,a-s .

# install everything into the package directory
cd $TMP
rm -rf $PKG
mkdir -p $PKG/install
mkdir -p $PKG/opt
mv JabRef $PKG/opt/$PRGNAM
cd $PKG/opt/$PRGNAM

# add to /usr/bin
mkdir -p $PKG/usr/bin
cat > $PKG/usr/bin/$PRGNAM << EOF
#!/bin/sh
/opt/$PRGNAM/bin/JabRef "\$@"
EOF
chmod +x $PKG/usr/bin/$PRGNAM

mkdir -p $PKG/usr/share/pixmaps
cp lib/JabRef.png $PKG/usr/share/pixmaps/

mkdir -p $PKG/usr/share/applications
cat > $PKG/usr/share/applications/$PRGNAM.desktop << EOF
[Desktop Entry]
Type=Application
Name=JabRef
GenericName=BibTeX Editor
Exec=/opt/$PRGNAM/bin/JabRef
Icon=JabRef
Categories=Office;
EOF

# add documentation
if [ "$DOCS" != "" ]; then
  mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
  cp -a $DOCS $PKG/usr/doc/$PRGNAM-$VERSION
  find $PKG/usr/doc/$PRGNAM-$VERSION -type f -exec chmod 644 {} \;
fi

# add some description to the package
if [ "$DESC" != "" ]; then
  echo "$DESC" | sed 's/^/'$PRGNAM': /g' > $PKG/install/slack-desc
fi

# append dependency information to the package
if [ "$REQUIRES" != "" ]; then
  for REQ in $REQUIRES; do
    echo "$REQ" >> $PKG/install/slack-required
  done
fi

# build the package
cd $PKG
PKGVERSION=$(echo $VERSION | sed 's/-/./g')
makepkg -l y -c n \
  $OUTPUT/$PRGNAM-$PKGVERSION-$ARCH-$BUILD$TAG.$PKGTYPE \
  || exit 1

# make everything clean
cd $CWD
rm -rf $PKG
