#!/bin/bash
# script for building extra printing drivers
# Epson, Canon, Pantum etc for Porteus
# Version 2025-12-28

# Copyright 2023-2030, Blaze, Dankov, Russia
# 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.

if [ "$(whoami)" != "root" ]; then
    echo -e "\nYou need to be root to run this script.\n"
    exit 1
fi

VERSION=$(date +%Y-%m-%d)
BUILD=${BUILD:-1}
BOLD=${BOLD:-"\e[1m"}
CYAN=${CYAN:-"\e[96m"}
GREEN=${GREEN:-"\e[92m"}
RED=${RED:-"\e[31m"}
RESET=${RESET:-"\e[0m"}
CWD=$(pwd)
TMPDIR=/tmp/portch
OUTPUT=${OUTPUT:-/tmp}
ARCH=$(uname -m)

PKG=""

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

cleanup(){
    [ -n "$TMPDIR" ] && [ -d "$TMPDIR" ] && rm -rf "$TMPDIR"
    [ -n "$PKG" ] && [ -d "$PKG" ] && rm -rf "$PKG"
    exit    
}

echo "Please set model of your printer for download and build extra printing module:"
echo "1) Canon"
echo "2) Epson"
echo "3) HP"
echo "4) Pantum"
echo "5) Samsung"
echo

read -r model

case "$model" in
1|Canon|canon)
echo -e "\n${BOLD}Canon${RESET} chosen. Downloading:"
PRGNAM=${PRGNAM:-canon}
PKG=${TMPDIR}/package-${PRGNAM}
PKGINFO=${PKG}/var/lib/pkgtools/packages
DEP1NAM=${DEPNAM:-jbigkit}
DEP1VER=$(lynx --source https://gitlab.archlinux.org/archlinux/packaging/packages/jbigkit/-/raw/main/.SRCINFO?ref_type=heads | grep pkgver | cut -d'=' -f2 | tr -d ' ')
SOURCE1=$(lynx --source https://aur.archlinux.org/packages/cnrdrvcups-lb-bin | grep -Eo "<a href=\"https://gdlp01.c-wss.com/gds/[^>]+")
SOURCE2=$(lynx --source https://aur.archlinux.org/packages/cnrdrvcups-sfp | grep -Eo "<a href=\"http://gdlp01.c-wss.com/gds/[^>]+")
SOURCE3=$(echo "http://www.cl.cam.ac.uk/~mgk25/jbigkit/download/jbigkit-${DEP1VER}.tar.gz")

rm -rf "$PKG"
mkdir -p "$TMPDIR" "$PKG" "$DEP1NAM-$DEP1VER"
cd "$PKG" || exit 1

wget -q --show-progress "$SOURCE1" "$SOURCE2" "$SOURCE3"
tar xf linux-UFRII-drv-*.tar.gz
tar xf linux-UFRIILT-drv-*.tar.gz
tar xf "jbigkit-${DEP1VER}.tar.gz"
rm -f *.tar.gz

cd "$DEP1NAM-$DEP1VER" || exit 1
wget -q "https://gitlab.archlinux.org/archlinux/packaging/packages/jbigkit/-/raw/main/jbigkit-${DEP1VER}-shared_lib.patch" \
     "https://gitlab.archlinux.org/archlinux/packaging/packages/jbigkit/-/raw/main/jbigkit-${DEP1VER}-build_warnings.patch" \
     "https://gitlab.archlinux.org/archlinux/packaging/packages/jbigkit/-/raw/main/jbigkit-${DEP1VER}-ldflags.patch" \
     "https://gitlab.archlinux.org/archlinux/packaging/packages/jbigkit/-/raw/main/jbigkit-${DEP1VER}-coverity.patch" \
     "https://gitlab.archlinux.org/archlinux/packaging/packages/jbigkit/-/raw/main/0013-new-jbig.c-limit-s-maxmem-maximum-decoded-image-size.patch" \
     "https://gitlab.archlinux.org/archlinux/packaging/packages/jbigkit/-/raw/main/0015-jbg_newlen-check-for-end-of-file-within-MARKER_NEWLE.patch"

patch -Np1 -i "jbigkit-${DEP1VER}-shared_lib.patch"
patch -Np1 -i "jbigkit-${DEP1VER}-build_warnings.patch"
patch -Np1 -i "jbigkit-${DEP1VER}-ldflags.patch"
patch -Np1 -i "jbigkit-${DEP1VER}-coverity.patch"
patch -Np1 -i "0013-new-jbig.c-limit-s-maxmem-maximum-decoded-image-size.patch"
patch -Np1 -i "0015-jbg_newlen-check-for-end-of-file-within-MARKER_NEWLE.patch"

make EXTRA_CFLAGS="$SLKCFLAGS"
mkdir -p "$PKG/usr/bin" "$PKG/usr/lib${LIBDIRSUFFIX}"

install -vDm 755 libjbig/*.so.* -t "$PKG/usr/lib${LIBDIRSUFFIX}"
for lib in libjbig.so libjbig85.so; do
    ln -sv "$lib.$DEP1VER" "$PKG/usr/lib${LIBDIRSUFFIX}/$lib"
done
install -vDm 755 pbmtools/{jbgtopbm{,85},pbmtojbg{,85}} -t "$PKG/usr/bin"

mkdir -p "$PKGINFO"
echo "PACKAGE NAME: $DEP1NAM-$DEP1VER-$ARCH" > "$PKGINFO/$DEP1NAM-$DEP1VER-$ARCH"

cat >> "$PKGINFO/$DEP1NAM-$DEP1VER-$ARCH" << EOM
PACKAGE DESCRIPTION:
jbigkit: jbigkit (highly effective lossless compression algorithm)
jbigkit:
jbigkit: JBIG is a highly effective lossless compression algorithm for
jbigkit: high-resolution bi-level images (one bit per pixel), which is
jbigkit: particularly suitable for scanned documents or fax pages.
jbigkit:
jbigkit: JBIG-KIT provides a portable library of compression and decompression
jbigkit: functions with a documented interface that you can easily include
jbigkit: into your image or document processing software. JBIG-KIT also
jbigkit: provides ready-to-use compression and decompression programs with a
jbigkit: simple command line interface.
FILE LIST:
EOM

find . | grep -v var >> "$PKGINFO/$DEP1NAM-$DEP1VER-$ARCH"

cd "$PKG" || exit 1
if [[ "$ARCH" == i686 || "$ARCH" == i586 ]]; then
    mv "$PKG"/linux-UFRII-drv-*-m17n/x86/Debian/cnrdrvcups-ufr2-uk_*_i386.deb "$PKG/"
    mv "$PKG"/linux-UFRIILT-drv-*-uken/32-bit_Driver/Debian/cnrdrvcups-ufr2lt-uk_*_i386.deb "$PKG/"
else
    mv "$PKG"/linux-UFRII-drv-*-m17n/x64/Debian/cnrdrvcups-ufr2-uk_*_amd64.deb "$PKG/"
    mv "$PKG"/linux-UFRIILT-drv-*-uken/64-bit_Driver/Debian/cnrdrvcups-ufr2lt-uk_*_amd64.deb "$PKG/"
fi

rm -rf "$PKG"/linux-UFRII-drv-*-m17n "$PKG"/linux-UFRIILT-drv-*-uken

DEP2NAM=${DEP2NAM:-cnrdrvcups-ufr2-uk}
DEP3NAM=${DEP3NAM:-cnrdrvcups-ufr2lt-uk}
DEP2VER=$(ar p "$PKG"/${DEP2NAM}_*.deb control.tar.xz 2>/dev/null | tar -OJxf - ./control | awk '/^Version:/{print $NF}')
DEP3VER=$(ar p "$PKG"/${DEP3NAM}_*.deb control.tar.gz 2>/dev/null | tar -Ozxf - ./control | awk '/^Version:/{print $NF}')

ar p "${DEP2NAM}"_*.deb data.tar.xz | tar Jx -C .
ar p "${DEP3NAM}"_*.deb data.tar.gz | tar zx -C .

echo "PACKAGE NAME: $DEP2NAM-$DEP2VER-$ARCH" > "$PKGINFO/$DEP2NAM-$DEP2VER-$ARCH"
cat >> "$PKGINFO/$DEP2NAM-$DEP2VER-$ARCH" << EOM
PACKAGE DESCRIPTION:
cnrdrvcups-ufr2-uk: CUPS Canon UFR II LIPSLX CARPS2 printer driver for LBP iR MF
cnrdrvcups-ufr2-uk: ImageCLASS ImageRUNNER Laser Shot i-SENSYS ImagePRESS ADVANCE
cnrdrvcups-ufr2-uk: printers and copiers
FILE LIST:
EOM

echo "PACKAGE NAME: $DEP3NAM-$DEP3VER-$ARCH" > "$PKGINFO/$DEP3NAM-$DEP3VER-$ARCH"
cat >> "$PKGINFO/$DEP3NAM-$DEP3VER-$ARCH" << EOM
PACKAGE DESCRIPTION:
cnrdrvcups-ufr2lt-uk: Canon UFRII LT Printer Driver for Linux
cnrdrvcups-ufr2lt-uk: (LBP112/912, LBP113/913, LBP151dw, LBP6030/LBP6040/LBP6018L,
cnrdrvcups-ufr2lt-uk: LBP6230/LBP6240, LBP7100C/LBP7110C, LBP8100)
FILE LIST:
EOM

rm -rf "$PKG/$DEP1NAM-$DEP1VER" "$PKG"/linux-UFRII-drv-v* "$PKG"/linux-UFRIILT-drv-v* "$PKG"/*.deb
rm -rf "$PKG/usr/include" "$PKG/usr/lib${LIBDIRSUFFIX}/pkgconfig" "$PKG/usr/share/locale"
rm -f "$PKG/usr/bin/"{cnsetuputil2,cnsetuputil2l} "$PKG/usr/share/applications/"{cnsetuputil.desktop,cnsetuputil2l.desktop}
rm -rf "$PKG/usr/share/"{cnsetuputil2,cnsetuputil2l,doc,man}

find "$PKG/usr/lib/Canon/CUPS_SFPR/Utilities/Message" -mindepth 1 -maxdepth 1 -type d ! -name 'Message' ! -name 'en_US' -exec rm -rf {} + 2>/dev/null || true

if [[ "$ARCH" == x86_64 ]]; then
    if [ -d "$PKG/usr/lib" ]; then
        cp -r "$PKG/usr/lib/"* "$PKG/usr/lib64/"
        rm -rf "$PKG/usr/lib"
    fi
fi

# Set correct ownership and permissions for CUPS backends and filters
for libdir in "$PKG/usr/lib" "$PKG/usr/lib64"; do
    if [ -d "$libdir/cups/backend" ]; then
        find "$libdir/cups/backend" -type f -exec chown root:lp {} \; -exec chmod 0700 {} \; 2>/dev/null
    fi
    if [ -d "$libdir/cups/filter" ]; then
        find "$libdir/cups/filter" -type f -exec chown root:lp {} \; -exec chmod 0755 {} \; 2>/dev/null
    fi
done

# Strip ELF binaries and shared libraries to reduce module size
find "$PKG/usr/lib" "$PKG/usr/lib64" -type f -name "*.so*" -exec strip --strip-unneeded {} \; 2>/dev/null
find "$PKG/usr/bin" "$PKG/usr/sbin" -type f -exec strip --strip-unneeded {} \; 2>/dev/null

dir2xzm "$PKG" "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm"

if [ -f "$OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}.xzm" ]; then
    echo -e "\n${BOLD}Your $PRGNAM module is at: ${GREEN}${BOLD}$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm${RESET}\n${BOLD}Please copy it to your modules folder to survive a reboot.${RESET}"
else
    echo -e "\n${RED}${BOLD}Failed. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
;;

2|Epson|epson)
echo -e "\n${BOLD}Epson${RESET} chosen. Downloading:"
PRGNAM=${PRGNAM:-epson}
PNAM=${PNAM:-epson-inkjet-printer-escpr}
PNAM2=${PNAM2:-epson-inkjet-printer-escpr2}
PKG=${TMPDIR}/package-${PRGNAM}
PKGINFO=${PKG}/var/lib/pkgtools/packages
SLACKESCPR=$(lynx --source https://slackbuilds.org/slackbuilds/15.0/system/epson-inkjet-printer-escpr/epson-inkjet-printer-escpr.info | grep -i version | cut -d'"' -f2)
ARCHESCPR=$(lynx --source https://aur.archlinux.org/packages/epson-inkjet-printer-escpr | grep "Details" | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+")
SLACKESCPR2=$(lynx --source https://slackbuilds.org/slackbuilds/15.0/system/epson-inkjet-printer-escpr2/epson-inkjet-printer-escpr2.info | grep -i version | cut -d'"' -f2)
ARCHESCPR2=$(lynx --source https://aur.archlinux.org/packages/epson-inkjet-printer-escpr2 | grep "Details" | grep -Eo "[0-9]+\.[0-9]+\.[0-9]{2}")
SOURCE1=$(echo "https://slackbuilds.org/slackbuilds/15.0/system/epson-inkjet-printer-escpr.tar.gz")
SOURCE2=$(lynx --source https://aur.archlinux.org/packages/epson-inkjet-printer-escpr | grep -Eo "<a href=\"https://download3.ebz.epson.net[^>]+")
SOURCE3=$(echo "https://slackbuilds.org/slackbuilds/15.0/system/epson-inkjet-printer-escpr2.tar.gz")
SOURCE4=$(lynx --source https://slackbuilds.org/repository/15.0/system/epson-inkjet-printer-escpr2/ | grep ".src.rpm" | cut -d'"' -f2)

rm -rf "$PKG"
find "${OUTPUT}" -maxdepth 1 -type f \( -name "*.tgz" -o -name "*.txz" \) -delete
mkdir -p "$TMPDIR" "$PKG"
cd "$PKG" || exit 1

getmod -q cups
activate "$OUTPUT"/cups-*.xzm

wget -q --show-progress "$SOURCE1"
tar -xf "$PNAM.tar.gz" && rm -f "$PNAM.tar.gz" && cd "$PNAM" || exit 1
wget -q --show-progress "$SOURCE2"

rpm2cpio "$PNAM"-*.src.rpm | cpio -idmv >/dev/null && rm -f "$PNAM"-*.src.rpm
sed -i "s|$SLACKESCPR|$ARCHESCPR|" "$PNAM.SlackBuild"
sed -i "s|1lsb3.2|1|" "$PNAM.SlackBuild"
sed -i "s|-mtune=i686|-mtune=i686 -Wno-implicit-function-declaration|g" "$PNAM.SlackBuild"
sed -i "s|-fPIC|-fPIC -Wno-implicit-function-declaration|" "$PNAM.SlackBuild"
./"$PNAM.SlackBuild"
cd "$PKG" && rm -rf "$PNAM"

wget -q --show-progress "$SOURCE3"
tar -xf "$PNAM2.tar.gz" && rm -f "$PNAM2.tar.gz" && cd "$PNAM2" || exit 1
wget -q --show-progress "$SOURCE4"

sed -i "s|-mtune=i686|-mtune=i686 -Wno-implicit-function-declaration|g" "$PNAM2.SlackBuild"
sed -i "s|-fPIC|-fPIC -Wno-implicit-function-declaration|g" "$PNAM2.SlackBuild"
./"$PNAM2.SlackBuild"
cd "$PKG" && rm -rf "$PNAM2"

find "${OUTPUT}" -maxdepth 1 -type f -name "*.tgz" -print0 | while IFS= read -r -d '' i; do 
    ROOT="$PKG" installpkg "$i" >/dev/null
done
deactivate "$OUTPUT"/cups-*.xzm

rm -rf "$PKG/usr/doc" "$PKG/var/lib/pkgtools/scripts"
find "${OUTPUT}" -maxdepth 1 -type f \( -name "*.tgz" -o -name "*.txz" -o -name "*.xzm" \) -delete

# Set correct ownership and permissions for CUPS backends and filters
for libdir in "$PKG/usr/lib" "$PKG/usr/lib64"; do
    if [ -d "$libdir/cups/backend" ]; then
        find "$libdir/cups/backend" -type f -exec chown root:lp {} \; -exec chmod 0700 {} \; 2>/dev/null
    fi
    if [ -d "$libdir/cups/filter" ]; then
        find "$libdir/cups/filter" -type f -exec chown root:lp {} \; -exec chmod 0755 {} \; 2>/dev/null
    fi
done

# Strip ELF binaries and shared libraries to reduce module size
find "$PKG/usr/lib" "$PKG/usr/lib64" -type f -name "*.so*" -exec strip --strip-unneeded {} \; 2>/dev/null
find "$PKG/usr/bin" "$PKG/usr/sbin" -type f -exec strip --strip-unneeded {} \; 2>/dev/null

dir2xzm "$PKG" "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm"

if [ -f "$OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}.xzm" ]; then
    echo -e "\n${BOLD}Your $PRGNAM module is at: ${GREEN}${BOLD}$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm${RESET}\n${BOLD}Please copy it to your modules folder to survive a reboot.${RESET}"
else
    echo -e "\n${RED}${BOLD}Failed. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
;;

3|HP|hp)
echo -e "\n${BOLD}HP${RESET} chosen. Downloading:"
PRGNAM=${PRGNAM:-hp}
UAGENT=$(echo 'Mozilla/5.0 (X11; Porteus Lynx; Linux x86_64; rv:139.0)')
SLACKVER=$(lynx --source https://slackbuilds.org/slackbuilds/15.0/system/hplip-plugin/hplip-plugin.info | grep -i version | cut -d'"' -f2)
PLUGVER=$(lynx -useragent="$UAGENT" --source https://www.openprinting.org/download/printdriver/auxfiles/HP/plugins/ | grep -oP 'hplip-\K[0-9.]+(?=-plugin.run)' | sort -V | tail -n1)
PKG=${TMPDIR}/package-${PRGNAM}
PKGINFO=${PKG}/var/lib/pkgtools/packages
SOURCE=$(echo "https://slackbuilds.org/slackbuilds/15.0/system/hplip-plugin.tar.gz")

rm -rf "$PKG"
find "${OUTPUT}" -maxdepth 1 -type f \( -name "*.tgz" -o -name "*.txz" \) -delete
mkdir -p "$TMPDIR" "$PKG"

cd "$PKG" || exit 1

getpkg -q hplip net-snmp

wget -q "$SOURCE"
tar xf hplip-plugin.tar.gz && rm -f hplip-plugin.tar.gz
cd hplip-plugin || exit 1
sed -i "s|$SLACKVER|$PLUGVER|" hplip-plugin.SlackBuild
wget -q --show-progress --user-agent="$UAGENT" "https://www.openprinting.org/download/printdriver/auxfiles/HP/plugins/hplip-${PLUGVER}-plugin.run"
./hplip-plugin.SlackBuild
cd "$PKG" && rm -rf hplip-plugin

find "${OUTPUT}" -maxdepth 1 -type f -name "*.txz" -print0 | while IFS= read -r -d '' i; do ROOT="${PKG}" installpkg "${i}" >/dev/null; done
find "${OUTPUT}" -maxdepth 1 -type f -name "*.tgz" -print0 | while IFS= read -r -d '' i; do ROOT="${PKG}" installpkg "${i}" >/dev/null; done

rm -rf "$PKG/usr/doc" "$PKG/usr/lib/systemd" "$PKG/usr/man" "${PKG}/usr/share/applications" "${PKG}/usr/share/hplip/data/"{images,localization} "$PKG/var/lib/pkgtools/scripts"
rm -f "${PKG}/etc/xdg/autostart/hplip-systray.desktop"
find "${PKG}" -type f \( -name "*.la" -o -name "*.a" -o -name "*.h" -o -iname "README*" -o -iname "LICENSE*" \) -delete
find "${OUTPUT}" -maxdepth 1 -type f \( -name "*.tgz" -o -name "*.txz" \) -delete

# Set correct ownership and permissions for CUPS backends and filters
for libdir in "$PKG/usr/lib" "$PKG/usr/lib64"; do
    if [ -d "$libdir/cups/backend" ]; then
        find "$libdir/cups/backend" -type f -exec chown root:lp {} \; -exec chmod 0700 {} \; 2>/dev/null
    fi
    if [ -d "$libdir/cups/filter" ]; then
        find "$libdir/cups/filter" -type f -exec chown root:lp {} \; -exec chmod 0755 {} \; 2>/dev/null
    fi
done

# Strip ELF binaries and shared libraries to reduce module size
find "$PKG/usr/lib" "$PKG/usr/lib64" -type f -name "*.so*" -exec strip --strip-unneeded {} \; 2>/dev/null
find "$PKG/usr/bin" "$PKG/usr/sbin" -type f -exec strip --strip-unneeded {} \; 2>/dev/null

dir2xzm "$PKG" "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm"

if [ -f "$OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}.xzm" ]; then
    echo -e "\n${BOLD}Your $PRGNAM module is at: ${GREEN}${BOLD}$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm${RESET}\n${BOLD}Please copy it to your modules folder to survive a reboot.${RESET}"
else
    echo -e "\n${RED}${BOLD}Failed. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
;;

4|Pantum|pantum)
echo -e "\n${BOLD}Pantum${RESET} chosen. Downloading:"
PRGNAM=${PRGNAM:-pantum}
PANVER=$(lynx -head -dump "https://github.com/ArticExploit/pantum-driver/releases/latest" | grep Location | grep -o "[0-9].*$" | tr -d '\r')
PKG=${TMPDIR}/package-${PRGNAM}
PKGINFO=${PKG}/var/lib/pkgtools/packages
SOURCE=$(lynx --source https://aur.archlinux.org/packages/pantum-driver | grep -Eo "<a href=\"https://github.com/ArticExploit/pantum-driver/releases/download/[^>]+")

rm -rf "$PKG"
find "${OUTPUT}" -maxdepth 1 -type f \( -name "*.tgz" -o -name "*.txz" \) -delete
mkdir -p "$TMPDIR" "$PKG"

cd "${OUTPUT}" || exit 1

wget -q --show-progress -P "${OUTPUT}" "$SOURCE"
unzip -q -d "${OUTPUT}" "Pantum.Ubuntu.Driver*.zip"
rm -f "${OUTPUT}"/Pantum.Ubuntu.Driver*.zip

PANTUM_DIR=$(find "${OUTPUT}" -maxdepth 1 -type d -name "Pantum Ubuntu Driver V*" | head -n 1)
if [ -z "$PANTUM_DIR" ]; then
    echo -e "\n${RED}${BOLD}Failed to find Pantum driver directory. Check the downloaded archive name.${RESET}\n"
    cleanup
fi
cd "${PANTUM_DIR}/Resources" || exit 1

if [[ "$ARCH" == i686 || "$ARCH" == i586 ]]; then
    mkdir -p "pantum-${PANVER}-i386"
    cd "pantum-${PANVER}-i386" || exit 1
    ar p "../pantum_${PANVER}-1_i386.deb" data.tar.xz | tar xJ
    cd usr/lib || exit 1
    cp -a i386-linux-gnu/* .
    rm -r *-linux-gnu*
    cd ../..
    rm -rf usr/local
    cp -a "${OUTPUT}/Pantum Ubuntu Driver V${PANVER}/Resources/pantum-${PANVER}-i386" "$PKG"
    cp -a "$PKG/pantum-${PANVER}-i386/"* "$PKG/"
elif [[ "$ARCH" == x86_64 ]]; then
    mkdir -p "pantum-${PANVER}-${ARCH}"
    cd "pantum-${PANVER}-${ARCH}" || exit 1
    ar p "../pantum_${PANVER}-1_amd64.deb" data.tar.xz | tar xJ
    cd usr/lib || exit 1
    mv x86_64-linux-gnu ../lib64
    cp -a cups ../lib64
    cd ../..
    rm -rf usr/local usr/lib
    cp -a "${OUTPUT}/Pantum Ubuntu Driver V${PANVER}/Resources/pantum-${PANVER}-${ARCH}" "$PKG"
    cp -a "$PKG/pantum-${PANVER}-${ARCH}/"* "$PKG/"
fi

rm -rf "${OUTPUT}/Pantum Ubuntu Driver V${PANVER}" "$PKG/pantum-${PANVER}-${ARCH}" "${PKG}/usr/share/doc"

cd "$PKG" || exit 1

ln -s "/usr/lib${LIBDIRSUFFIX}/libjpeg.so.62" "$PKG/usr/lib${LIBDIRSUFFIX}/libjpeg.so.8"

mkdir -p "$PKGINFO"
echo "PACKAGE NAME: $PRGNAM-$PANVER-$ARCH" > "$PKGINFO/$PRGNAM-$PANVER-$ARCH"

cat >> "$PKGINFO/$PRGNAM-$PANVER-$ARCH" << EOM
PACKAGE DESCRIPTION:
pantum: Linux driver for Pantum printers
FILE LIST:
EOM

find . | grep -v var >> "$PKGINFO/$PRGNAM-$PANVER-$ARCH"

# Set correct ownership and permissions for CUPS backends and filters
for libdir in "$PKG/usr/lib" "$PKG/usr/lib64"; do
    if [ -d "$libdir/cups/backend" ]; then
        find "$libdir/cups/backend" -type f -exec chown root:lp {} \; -exec chmod 0700 {} \; 2>/dev/null
    fi
    if [ -d "$libdir/cups/filter" ]; then
        find "$libdir/cups/filter" -type f -exec chown root:lp {} \; -exec chmod 0755 {} \; 2>/dev/null
    fi
done

# Strip ELF binaries and shared libraries to reduce module size
find "$PKG/usr/lib" "$PKG/usr/lib64" -type f -name "*.so*" -exec strip --strip-unneeded {} \; 2>/dev/null
find "$PKG/usr/bin" "$PKG/usr/sbin" -type f -exec strip --strip-unneeded {} \; 2>/dev/null

dir2xzm "$PKG" "$OUTPUT/$PRGNAM-$PANVER-$ARCH-$BUILD.xzm"

if [ -f "$OUTPUT/${PRGNAM}-${PANVER}-${ARCH}-${BUILD}.xzm" ]; then
    echo -e "\n${BOLD}Your $PRGNAM module is at: ${GREEN}${BOLD}$OUTPUT/$PRGNAM-$PANVER-$ARCH-$BUILD.xzm${RESET}\n${BOLD}Please copy it to your modules folder to survive a reboot.${RESET}"
else
    echo -e "\n${RED}${BOLD}Failed. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
;;

5|Samsung|samsung)
echo -e "\n${BOLD}Samsung${RESET} chosen. Downloading:"
PRGNAM=${PRGNAM:-samsung-unified-driver}
VERSION=V1.00.39
PKG=${TMPDIR}/package-${PRGNAM}
PKGINFO=${PKG}/var/lib/pkgtools/packages
SOURCE1=$(echo "http://downloadcenter.samsung.com/content/DR/201704/20170407143829533/uld_V1.00.39_01.17.tar.gz")
SOURCE2=$(echo "https://aur.archlinux.org/cgit/aur.git/plain/xerox_mfp-smfp.conf?h=samsung-unified-driver")

rm -rf "$PKG"
find "${OUTPUT}" -maxdepth 1 -type f \( -name "*.tgz" -o -name "*.txz" \) -delete
mkdir -p "$TMPDIR" "$PKG"

cd "$OUTPUT" || exit 1

wget -q --show-progress -P "${OUTPUT}" "$SOURCE1"
tar -xf uld_${VERSION}_*.tar.gz && rm -f uld_${VERSION}_*.tar.gz

if [ "$ARCH" = "i586" ] || [ "$ARCH" = "i686" ]; then
    mkdir -p "$PKG/usr/lib" "$PKG/usr/lib/cups/backend" "$PKG/usr/lib/cups/filter" "$PKG/usr/share/ppd/suld" "$PKG/usr/share/ppd/suld/cms"
    cp "$OUTPUT/uld/i386/libscmssc.so" "$PKG/usr/lib/"
    cp "$OUTPUT/uld/i386/smfpnetdiscovery" "$PKG/usr/lib/cups/backend/"
    cp "$OUTPUT/uld/i386/pstosecps" "$PKG/usr/lib/cups/filter/"
    cp "$OUTPUT/uld/i386/rastertospl" "$PKG/usr/lib/cups/filter/"
    ln -s rastertospl "$PKG/usr/lib/cups/filter/rastertosplc"

    for ppd in "$OUTPUT"/uld/noarch/share/ppd/*.ppd; do
        gzip < "$ppd" > "$PKG/usr/share/ppd/suld/${ppd##*/}.gz"
    done
    for cts in "$OUTPUT"/uld/noarch/share/ppd/cms/*.cts; do
        cp "$cts" "$PKG/usr/share/ppd/suld/cms/"
    done
fi

if [ "$ARCH" = "x86_64" ]; then
    mkdir -p "$PKG/usr/lib64" "$PKG/usr/lib64/cups/backend" "$PKG/usr/lib64/cups/filter" "$PKG/usr/share/ppd/suld" "$PKG/usr/share/ppd/suld/cms"
    cp "$OUTPUT/uld/x86_64/libscmssc.so" "$PKG/usr/lib64/"
    cp "$OUTPUT/uld/x86_64/smfpnetdiscovery" "$PKG/usr/lib64/cups/backend/"
    cp "$OUTPUT/uld/x86_64/pstosecps" "$PKG/usr/lib64/cups/filter/"
    cp "$OUTPUT/uld/x86_64/rastertospl" "$PKG/usr/lib64/cups/filter/"
    ln -s rastertospl "$PKG/usr/lib64/cups/filter/rastertosplc"

    for ppd in "$OUTPUT"/uld/noarch/share/ppd/*.ppd; do
        gzip < "$ppd" > "$PKG/usr/share/ppd/suld/${ppd##*/}.gz"
    done
    for cts in "$OUTPUT"/uld/noarch/share/ppd/cms/*.cts; do
        cp "$cts" "$PKG/usr/share/ppd/suld/cms/"
    done
fi

if [ "$ARCH" = "i586" ] || [ "$ARCH" = "i686" ]; then
    mkdir -p "$PKG/etc/sane.d" "$PKG/etc/sane.d/dll.d" "$PKG/usr/lib/sane" "$PKG/etc/udev/rules.d" "$PKG/opt/samsung/scanner/share"
    lynx --source "$SOURCE2" > "$OUTPUT/xerox_mfp-smfp.conf"
    cp "$OUTPUT/uld/noarch/etc/smfp.conf" "$OUTPUT/xerox_mfp-smfp.conf" "$PKG/etc/sane.d/"
    echo smfp > "$PKG/etc/sane.d/dll.d/smfp-scanner"
    echo xerox_mfp-smfp > "$PKG/etc/sane.d/dll.d/smfp-scanner-fix"
    cp "$OUTPUT/uld/i386/libsane-smfp.so.1.0.1" "$PKG/usr/lib/sane/"
    ln -s libsane-smfp.so.1.0.1 "$PKG/usr/lib/sane/libsane-smfp.so.1"
    ln -s libsane-smfp.so.1 "$PKG/usr/lib/sane/libsane-smfp.so"
    (
        OEM_FILE="$OUTPUT/uld/noarch/oem.conf"
        INSTALL_LOG_FILE=/dev/null
        source "$OUTPUT/uld/noarch/scripting_utils"
        source "$OUTPUT/uld/noarch/package_utils"
        source "$OUTPUT/uld/noarch/scanner-script.pkg"
        fill_full_template "$OUTPUT/uld/noarch/etc/smfp.rules.in" "$PKG/etc/udev/rules.d/60_smfp_samsung.rules"
        chmod 644 "$PKG/etc/udev/rules.d/60_smfp_samsung.rules"
        cp "$OEM_FILE" "$PKG/opt/samsung/scanner/share/"
    )
fi

if [ "$ARCH" = "x86_64" ]; then
    mkdir -p "$PKG/etc/sane.d" "$PKG/etc/sane.d/dll.d" "$PKG/usr/lib64/sane" "$PKG/etc/udev/rules.d" "$PKG/opt/samsung/scanner/share"
    lynx --source "$SOURCE2" > "$OUTPUT/xerox_mfp-smfp.conf"
    cp "$OUTPUT/uld/noarch/etc/smfp.conf" "$OUTPUT/xerox_mfp-smfp.conf" "$PKG/etc/sane.d/"
    echo smfp > "$PKG/etc/sane.d/dll.d/smfp-scanner"
    echo xerox_mfp-smfp > "$PKG/etc/sane.d/dll.d/smfp-scanner-fix"
    cp "$OUTPUT/uld/x86_64/libsane-smfp.so.1.0.1" "$PKG/usr/lib64/sane/"
    ln -s libsane-smfp.so.1.0.1 "$PKG/usr/lib64/sane/libsane-smfp.so.1"
    ln -s libsane-smfp.so.1 "$PKG/usr/lib64/sane/libsane-smfp.so"
    (
        OEM_FILE="$OUTPUT/uld/noarch/oem.conf"
        INSTALL_LOG_FILE=/dev/null
        source "$OUTPUT/uld/noarch/scripting_utils"
        source "$OUTPUT/uld/noarch/package_utils"
        source "$OUTPUT/uld/noarch/scanner-script.pkg"
        fill_full_template "$OUTPUT/uld/noarch/etc/smfp.rules.in" "$PKG/etc/udev/rules.d/60_smfp_samsung.rules"
        chmod 644 "$PKG/etc/udev/rules.d/60_smfp_samsung.rules"
        cp "$OEM_FILE" "$PKG/opt/samsung/scanner/share/"
    )
fi

rm -rf "$OUTPUT/uld" "$OUTPUT/xerox_mfp-smfp.conf"

cd "$PKG" || exit 1

mkdir -p "$PKGINFO"
echo "PACKAGE NAME: $PRGNAM-$VERSION-$ARCH" > "$PKGINFO/$PRGNAM-$VERSION-$ARCH"

cat >> "$PKGINFO/$PRGNAM-$VERSION-$ARCH" << EOM
PACKAGE DESCRIPTION:
samsung-unified-driver: Samsung Unified Linux Driver for printers and scanners.
samsung-unified-driver:
samsung-unified-driver: http://www.samsung.com/
samsung-unified-driver:
FILE LIST:
EOM

find . | grep -v var >> "$PKGINFO/$PRGNAM-$VERSION-$ARCH"

# Set correct ownership and permissions for CUPS backends and filters
for libdir in "$PKG/usr/lib" "$PKG/usr/lib64"; do
    if [ -d "$libdir/cups/backend" ]; then
        find "$libdir/cups/backend" -type f -exec chown root:lp {} \; -exec chmod 0700 {} \; 2>/dev/null
    fi
    if [ -d "$libdir/cups/filter" ]; then
        find "$libdir/cups/filter" -type f -exec chown root:lp {} \; -exec chmod 0755 {} \; 2>/dev/null
    fi
done

# Strip ELF binaries and shared libraries to reduce module size
find "$PKG/usr/lib" "$PKG/usr/lib64" -type f -name "*.so*" -exec strip --strip-unneeded {} \; 2>/dev/null
find "$PKG/usr/bin" "$PKG/usr/sbin" -type f -exec strip --strip-unneeded {} \; 2>/dev/null

dir2xzm "$PKG" "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm"

if [ -f "$OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}.xzm" ]; then
    echo -e "\n${BOLD}Your $PRGNAM module is at: ${GREEN}${BOLD}$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm${RESET}\n${BOLD}Please copy it to your modules folder to survive a reboot.${RESET}"
else
    echo -e "\n${RED}${BOLD}Failed. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
;;

*)
echo "Sorry, but your model of printer is not in the list."
exit 0
;;
esac
