#!/bin/bash

APP_DIR=/opt/4barcode/printer-driver-4barcode

echo CPU_BITS: $(getconf LONG_BIT)
echo SYS_NAME: $(uname)
echo CPU_ARCH: $(uname -m)

if [ "Darwin" = $(uname) ];
then
    if [ "arm64" = $(uname -m) ];
    then
        CPU_ARCH="macarm64"
    elif [ "32" -eq $(getconf LONG_BIT) ];
    then
        CPU_ARCH="macx86"
    else
        CPU_ARCH="macx64"
    fi
elif [ "aarch64" = $(uname -m) ];
then
    CPU_ARCH="aarch64"
elif [ "armv7l" = $(uname -m) ];
then
    CPU_ARCH="armv7l"
elif [ "loongarch64" = $(uname -m) ];
then
    CPU_ARCH="loongarch64"
elif [ "mips64" = $(uname -m) ];
then
    CPU_ARCH="mips64"
elif [ "Linux" = $(uname) ];
then
    if [ "32" -eq $(getconf LONG_BIT) ];
    then
        CPU_ARCH="x86"
    else
        CPU_ARCH="x64"
    fi
else
    echo "Unsupported system!"
    exit 1
fi

if [ ! -z $DESTDIR ];
then
    echo "DESTDIR set to $DESTDIR"
    echo ""
fi

FILTER_DIR=/usr/lib/cups/filter

# Unpack the filters
cd "${APP_DIR}/bin"
tar xvf ../share/filters.tgz

# Fix the permissions and owner
chmod a+x "${APP_DIR}/bin/"*
chown -Rf root:root "${APP_DIR}"

# Remove the filter link first

rm -f "${FILTER_DIR}/rastertosnailtspl-4barcode"
ln -s ${APP_DIR}/bin/rastertosnailtspl-${CPU_ARCH} "${FILTER_DIR}/rastertosnailtspl-4barcode"

rm -f "${FILTER_DIR}/rastertosnailep-4barcode"
ln -s ${APP_DIR}/bin/rastertosnailep-${CPU_ARCH} "${FILTER_DIR}/rastertosnailep-4barcode"

rm -f "${FILTER_DIR}/rastertosnailep2-4barcode"
ln -s ${APP_DIR}/bin/rastertosnailep2-${CPU_ARCH} "${FILTER_DIR}/rastertosnailep2-4barcode"


grep -q "0x2D37 no-reattach soft-reset unidir" /usr/share/cups/usb/org.cups.usb-quirks
a=$?
if   [ $a -eq 0 ] || [ $a -eq 2 ]
then
    echo "USB device 0x2D37 already configured!"
else
    echo -e "\n0x2D37 no-reattach soft-reset unidir\n">>/usr/share/cups/usb/org.cups.usb-quirks
    echo "Configure USB device 0x2D37 ..."
fi

grep   -q "0x2D84 no-reattach soft-reset unidir" /usr/share/cups/usb/org.cups.usb-quirks
a=$?
if   [ $a -eq 0 ] || [ $a -eq 2 ]
then
    echo "USB device 0x2D84 already configured!"
else
    echo -e "\n0x2D84 no-reattach soft-reset unidir\n">>/usr/share/cups/usb/org.cups.usb-quirks
    echo "Configure USB device 0x2D84 ..."
fi

echo "Driver success installed!"
echo "Please navigate to http://localhost:631/ for manage your printers."
