#!/bin/bash
# script for building 07-printing base module for Porteus
# Version 2026-03-31

# 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.

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

PRGNAM=${PRGNAM:-07-printing}
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
PKG=${TMPDIR}/package-${PRGNAM}
PKGINFO=${PKG}/var/lib/pkgtools/packages
OUTPUT=${OUTPUT:-/tmp}
ARCH=$( uname -m )

systemFullVersion=$(cat /etc/slackware-version)
if [[ ${systemFullVersion//* } != *"+" ]]; then
export PORTEUSBUILD=stable
else
export PORTEUSBUILD=current
fi

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

rm -rf ${OUTPUT}/*.txz
mkdir -p ${TMPDIR} ${PKG}
cd ${PKG}

# Auto-detect Desktop Environment (for su/root cases)
if [ -z "$XDG_CURRENT_DESKTOP" ]; then
    if pgrep -x "cinnamon" > /dev/null; then XDG_CURRENT_DESKTOP="X-Cinnamon"
    elif pgrep -x "cosmic-session" > /dev/null; then XDG_CURRENT_DESKTOP="COSMIC"
    elif pgrep -x "gnome-session|gnome-shell|mutter" > /dev/null; then XDG_CURRENT_DESKTOP="GNOME"
    elif pgrep -x "ksmserver|plasmashell|kwin_wayland" > /dev/null; then XDG_CURRENT_DESKTOP="KDE"
    elif pgrep -x "lxsession" > /dev/null; then XDG_CURRENT_DESKTOP="LXDE"
    elif pgrep -x "lxqt-session" > /dev/null; then XDG_CURRENT_DESKTOP="LXQt"
    elif pgrep -x "mate-session" > /dev/null; then XDG_CURRENT_DESKTOP="MATE"
    elif pgrep -x "openbox" > /dev/null; then XDG_CURRENT_DESKTOP="openbox"
    elif pgrep -x "xfce4-session" > /dev/null; then XDG_CURRENT_DESKTOP="XFCE"
    fi
fi
export XDG_CURRENT_DESKTOP

# Package Fetching Logic (DE Awareness)
PRINTING_COMMON="cups cups-browsed cups-filters ghostscript gutenprint libcupsfilters libpaper libppd pycups pycurl python-notify2 qpdf system-config-printer"
DBUS_PY=""

# Add dbus-python (doesn't include Cinnamon and MATE)
if [[ "${XDG_CURRENT_DESKTOP,,}" == "gnome"   || \
      "${XDG_CURRENT_DESKTOP,,}" == "kde"     || \
      "${XDG_CURRENT_DESKTOP,,}" == "lxde"    || \
      "${XDG_CURRENT_DESKTOP,,}" == "lxqt"    || \
      "${XDG_CURRENT_DESKTOP,,}" == "xfce"    || \
      "${XDG_CURRENT_DESKTOP,,}" == "openbox" || \
      "${XDG_DESKTOP_SESSION,,}" == "openbox" ]]; then
    DBUS_PY="dbus-python"
fi

if [[ -z "$DBUS_PY" && ( "${XDG_CURRENT_DESKTOP,,}" == "x-cinnamon" || "${XDG_CURRENT_DESKTOP,,}" == "mate" ) ]]; then
    getpkg -q $PRINTING_COMMON
else
    getpkg -q $PRINTING_COMMON dbus-python
fi

for i in $(find ${OUTPUT} -type f -name "*.txz"); do ROOT=${PKG} installpkg ${i} >/dev/null; done

rm -f ${OUTPUT}/*.{txz,tgz}

# tweaks
chmod +x ${PKG}/etc/rc.d/rc.cups
sed -i 's|localhost:631|localhost:631/admin|' ${PKG}/usr/share/applications/cups.desktop
sed -i 's|# Only listen for connections from the local machine.|# Allow remote access|' ${PKG}/etc/cups/cupsd.conf
sed -i 's|Listen localhost:631|Port 631|' ${PKG}/etc/cups/cupsd.conf
sed -i "s|  Order allow,deny|  Order allow,deny\n  Allow all|g" ${PKG}/etc/cups/cupsd.conf

# cleanup
rm -rf ${PKG}/usr/{doc,man,include,info,src}
rm -rf ${PKG}/usr/lib/{.build-id,cmake,libgphoto2_port,systemd}
rm -rf ${PKG}/usr/lib{,64}/{cmake,girepository-1.0,pkgconfig}
rm -rf ${PKG}/usr/lib{,64}/gutenprint/*.*/config.summary
rm -rf ${PKG}/usr/lib{,64}/python*/site-packages/*.{dist-info,egg,egg-info}
rm -rf ${PKG}/usr/share/{doc,gir-1.0,gtk-doc,help,icons,licenses,pkgconfig}
rm -rf ${PKG}/usr/share/ghostscript/*.*/{doc,examples}
rm -rf ${PKG}/usr/share/gutenprint/samples
rm -rf ${PKG}/var/lib/pkgtools/douninst.sh
rm -f ${PKG}/var/log/scripts/*
find ${PKG} -type f -name "*.la" -delete
find ${PKG} -type f -name "*.a" -delete
find ${PKG} -type f -name "*.h" -delete
find ${PKG} -type f -iname "README*" -delete
find ${PKG} -type f -iname "LICENSE*" -delete
find ${PKG}/usr/share/locale -type f ! -name 'system-config-printer.mo' -delete
rm -rf ${OUTPUT}/SBo

## functions to choose locale from a menu
array_menu(){
echo
echo "$1"
echo "$2"
select CHOICE in ${RESULT[@]}; do
	if [ -z "$CHOICE" ]; then
        CHOICE="en_US"
		echo "English locale chosen." && echo
			else
		echo -e "${BOLD}${CYAN}${CHOICE}${RESET} locale chosen"
	fi
	break
done
}

get_locale(){
# Set locales in array
for a in ar as ast bg bn bn_IN br bs ca cs cy da de el en_GB en_US es et fa fi fr fur gu he hi hr hu id is it ja ka kn ko lt lv mai ml mr ms nb nds nl nn oc or pa pl pt pt_BR ro ru si sk sl sr 'sr\@latin' sv ta te th tr uk vi zh_CN zh_TW; do
	RESULT+=( $a )
done

array_menu "Choose a locale from the list." "All other locales will be removed." ${RESULT[@]}
unset RESULT
}

get_locale

echo "Removing locales ..."
find $PKG/usr/share/locale -maxdepth 1 -type d ! -name 'locale' | grep -Ev "${CHOICE}" | xargs -i rm -rf {}
find $PKG/usr/share/cups/templates -maxdepth 1 -type d ! -name 'templates' | grep -Ev "${CHOICE}" | xargs -i rm -rf {}

dir2xzm ${PKG} $OUTPUT/$PRGNAM-$PORTEUSBUILD-$VERSION-$ARCH-$BUILD.xzm

# check on printing xzm file exists in /tmp
if [ -f "$OUTPUT/${PRGNAM}-${PORTEUSBUILD}-${VERSION}-${ARCH}-${BUILD}.xzm" ]; then
    echo -e "\n${BOLD}Your ${PRGNAM} module is at: ${GREEN}${BOLD}${OUTPUT}/${PRGNAM}-${PORTEUSBUILD}-${VERSION}-${ARCH}-${BUILD}.xzm${RESET}\n${BOLD}Please copy it to your ${BASEDIR}/porteus/base folder to survive a reboot.${RESET}\n"
else
    echo -e "\n${RED}${BOLD}Faile. Your ${PRGNAM} module is not built.${RESET}\n"
fi
cleanup
