#!/bin/sh
#
# foo2zjs.SlackBuild
# 2020-06-27
#
# a linux printer driver for ZjStream protocol

PRGNAM=foo2zjs
MODEL=${MODEL:-1600}   # Get HP Color LaserJet 1600 .ICM files
VERSION=20200610

# automatically determine the architecture
if [ -z "$ARCH" ]; then
  ARCH=$(uname -m)
fi

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

HOMEPAGE="http://foo2zjs.rkkda.com/"
SOURCE="${PRGNAM}.tar.gz"
DOWNLOAD="${HOMEPAGE}${SOURCE}"
MD5SUM="5be13b7873c2b7099e5236e4a0f11005"

REQUIRES=""

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

DESC="a linux printer driver for ZjStream protocol

${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 $PRGNAM || exit 1

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

# set options
if [ "$ARCH" = "x86_64" ]; then
  LIBDIRSUFFIX="64"
 else
  LIBDIRSUFFIX=""
fi

# compile the source
make || exit 1
./getweb $MODEL

# install everything into the package directory
rm -rf $PKG
mkdir -p $PKG/install
mkdir -p $PKG/usr/bin
mkdir -p $PKG/usr/man
mkdir -p $PKG/usr/doc/foo2zjs
mkdir -p $PKG/usr/share/cups/model
mkdir -p $PKG/usr/share/applications
mkdir -p $PKG/usr/share/pixmaps
mkdir -p $PKG/usr/lib$LIBDIRSUFFIX/cups/filter
make install \
  DESTDIR=$PKG \
  PREFIX=$PKG/usr \
  MANDIR=$PKG/usr/man \
  DOCDIR=$PKG/usr/doc/foo2zjs \
  || exit 1

# fix broken symbolic link
cd $PKG/usr/lib$LIBDIRSUFFIX/cups/filter
rm command2foo2lava-pjl
ln -s ../../../bin/command2foo2lava-pjl command2foo2lava-pjl

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

# compress man pages
if [ -d $PKG/usr/man ]; then
  find $PKG/usr/man -type f -name "*.?" -exec gzip -9 {} \;
  for i in $(find $PKG/usr/man -type l -name "*.?") ; do
    ln -s $(readlink $i).gz $i.gz
    rm $i
  done
fi

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

# add some description to the package
if [ "$DESC" != "" ]; then
  echo "$DESC" | sed 's/^/'$PRGNAM-$MODEL': /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
makepkg -l y -c n \
  $OUTPUT/$PRGNAM-$MODEL-$VERSION-$ARCH-$BUILD$TAG.${PKGTYPE:-tgz} \
  || exit 1

# make everything clean
cd $CWD
rm -rf $PKG
rm -rf $TMP/$PRGNAM
