#!/bin/bash

# This is NAPS2 update script for Porteus
# with support "driverless" scanning
# via eSCL (Apple AirScan) and WSD
# Version 2025-06-21

# 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:-naps2}
BUILD=${BUILD:-1}
ARCH=$( uname -m )
VERSION=$(lynx -head -dump "https://github.com/cyanfish/naps2/releases/latest" | grep Location | grep -o "v[0-9].*$" | tr -d v)
SOURCE=$(echo https://github.com/cyanfish/naps2/releases/download/v${VERSION}/${PRGNAM}-${VERSION}-linux-x64.deb)
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}
SLKCFLAGS="-O2 -fPIC"
CFLAGS="$SLKCFLAGS"
CXXFLAGS="$SLKCFLAGS"
SANAME=${SANAME:-sane-airscan}
SAVER=$(lynx --source "https://github.com/alexpevzner/sane-airscan/tags" | grep .zip | head -n1 | egrep -o '[0-9].[0-9]{2}.[0-9]{2}')
SAMASTER=$(echo https://github.com/alexpevzner/sane-airscan/archive/refs/heads/master.zip)

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

# check if NAPS2 installed in the system
if [[ -f "/usr/bin/naps2" ]]; then
  MYVER=${MYVER:-`ls /var/lib/pkgtools/packages/*naps2* | tail -n1 | cut -d'-' -f2`}
# MYVER=${MYVER:-`cat /usr/share/metainfo/com.naps2.Naps2.metainfo.xml | grep date= | cut -d'"' -f2`}
fi

if [ "$MYVER" == "$VERSION" ]; then
    echo -e "You have the latest ${GREEN}$MYVER${RESET} version of $PRGNAM"
    sleep 5
    exit
else
    read -p "$(echo -e 1\) Would you like to build $PRGNAM ${GREEN}$VERSION${RESET} xzm module? [y/n])" -n 1 -r -s && echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "We continue the execution of the $0 script" &>/dev/null
        else
        exit
    fi
fi

rm -rf $PKG
mkdir -p $TMPDIR $PKG
cd $PKG

# add support "driverless" scanning via eSCL (Apple AirScan) and WSD for most modern network scanners
read -p "$(echo -e 2\) Would you like to add support for ${BOLD}\"driverless\"${RESET} scanning via eSCL \(Apple AirScan\) and WSD? [y/n])" -n 1 -r -s && echo
if [[ $REPLY =~ ^[Yy]$ ]]; then

# sane-airscan involves compilation!
if [ ! -e /usr/bin/gcc ]; then
    echo -e "\nPlease activate 05-devel.xzm module and rerun this script.\n"
    exit 1
fi

# activate and install sane dep to $PKG
rm -rf ${OUTPUT}/*.txz
getmod -q sane universal-ctags && activate $OUTPUT/sane-*.xzm $OUTPUT/universal-ctags-*.xzm -q > /dev/null
XZM=no getpkg -q libieee1284
for i in $(find ${OUTPUT} -type f -name "*.txz"); do ROOT=${PKG} installpkg ${i} >/dev/null; done
rm -f ${OUTPUT}/{sane,libieee1284,universal-ctags}-*.txz

# build xzm module of sane-airscan
echo -e "\nCompiling ${BOLD}sane-airscan${RESET}"
cd $PKG && wget -q $SAMASTER
unzip -q master.zip -d $PKG && rm -f master.zip
cd sane-airscan-master

# fix bug with double // in the make file of sane-airscan
sed -i 's|$(DESTDIR)/|$(DESTDIR)|g' $PKG/sane-airscan-master/Makefile

chown -R root:root .
find -L . \
 \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 750 -o -perm 555 \
  -o -perm 511 \) -exec chmod 755 {} \; -o \
 \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 640 -o -perm 444 \
  -o -perm 440 -o -perm 400 \) -exec chmod 644 {} \;

make VERBOSE=1
make install DESTDIR=$PKG
cd $PKG && rm -rf $PKG/sane-airscan-master

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

### fake Slackware type package info: super dumb version
mkdir -p $PKGINFO
echo "PACKAGE NAME: $SANAME-$SAVER-$ARCH" > $PKGINFO/$PRGNAM-$VERSION-$ARCH

cat >> $PKGINFO/$SANAME-$SAVER-$ARCH << EOM
PACKAGE DESCRIPTION:
sane-airscan: sane-airscan (Scanner Access Now Easy)
sane-airscan:
sane-airscan: Scanner Access Now Easy - universal driver for
sane-airscan: eSCL (Apple AirScan) and WSD
sane-airscan:
sane-airscan:
sane-airscan:
sane-airscan: Homepage: https://github.com/alexpevzner/sane-airscan
sane-airscan:
sane-airscan:
sane-airscan:
FILE LIST:
EOM

# add missing .so symlink
cd $PKG/usr/lib64/sane
ln -sf libsane-airscan.so.1 libsane-airscan.so

# activate "airscan" backend for compatible with AirSane
# https://github.com/SimulPiscator/AirSane
sed -i 's|escl|#escl|' $PKG/etc/sane.d/dll.conf
sed -i '/apple/iairscan' $PKG/etc/sane.d/dll.conf

deactivate $OUTPUT/sane-*.xzm $OUTPUT/universal-ctags-*.xzm -q > /dev/null
rm -f $OUTPUT/{sane,universal-ctags}-*.xzm
cd $PKG

else

# no add AirScan support
# only install sane and libieee128 as deps to $PKG
rm -rf ${OUTPUT}/*.txz
XZM=no getpkg -q sane libieee1284
for i in $(find ${OUTPUT} -type f -name "*.txz"); do ROOT=${PKG} installpkg ${i} >/dev/null; done
rm -f ${OUTPUT}/{sane-*,libieee1284-*}.txz

fi

# download NAPS2
echo -e "\nDownloading ${BOLD}${PRGNAM}-${VERSION}${RESET}"
wget -q --show-progress "$SOURCE"

# check that we have an archive in TMPDIR
if [ ! -f ${PRGNAM}-${VERSION}-linux-x64.deb ]; then
	echo -e "\n${RED}${BOLD}Download seems to have failed, Exiting...${RESET}"
	cleanup
fi

# unpack packages
ar p ${PRGNAM}-${VERSION}-linux-x64.deb data.tar.xz | tar xJ

# cleanup
rm -f $PKG/*.deb
rm -rf $PKG/usr/{doc,man,include,info,src}
rm -rf $PKG/usr/lib64/pkgconfig
rm -f $PKG/usr/lib/naps2/*.txt
rm -rf $PKG/usr/share/{doc,gir-1.0,gtk-doc,help,licenses,locale,man,pkgconfig}
rm -rf $PKG/var/lib/pkgtools/douninst.sh
rm -f $PKG/var/log/scripts/*
find $PKG -type f -name "*.a" -delete
find $PKG -type f -name "*.la" -delete

# remove MIME types and add Russian translation
sed -i '/MimeType/d' $PKG/usr/share/applications/naps2.desktop
sed -i '/Name=/a Name[ru]=Сканер документов NAPS2' $PKG/usr/share/applications/naps2.desktop

### fake Slackware type package info: super dumb version
mkdir -p $PKGINFO
echo "PACKAGE NAME: $PRGNAM-$VERSION-$ARCH" > $PKGINFO/$PRGNAM-$VERSION-$ARCH

cat >> $PKGINFO/$PRGNAM-$VERSION-$ARCH << EOM
PACKAGE DESCRIPTION:
NAPS2: NAPS2 - Not Another PDF Scanner.
NAPS2:
NAPS2: Scan documents to PDF and more, as simply as possible.
NAPS2:
NAPS2: https://www.naps2.com
NAPS2:
FILE LIST:
EOM

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

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

# check on NAPS2 xzm file exists in /tmp
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}Faile. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup