#!/bin/bash

CUPS_PPD_ROOT="/usr/share/cups/model"
WORKDIR=$(cd "$(dirname "$0")"; pwd)
PACKAGES="$WORKDIR/packages"

RUN_KATUSHA_UNIVERSAL=to-install-katusha-UNIVERSAL-drivers
RUN_KATUSHA_M130=to-install-katusha-M130-drivers
RUN_KATUSHA_M247=to-install-katusha-M247-drivers
RUN_KATUSHA_M348=to-install-katusha-M348-drivers

#--
#-- Initialize_Variables helper function. Depending on the Linux OS, the path
#-- can either be: /usr/bin/command or /bin/command. So, lets set these
#-- dynamically.
#--
set_variable()
{
	VAR_NAME="${1}"
	CMD_NAME="${2}"
	if [ -f "/usr/bin/${CMD_NAME}" ];then
		eval ${VAR_NAME}="/usr/bin/${CMD_NAME}"
	elif [ -f "/bin/${CMD_NAME}" ];then
		eval ${VAR_NAME}="/bin/${CMD_NAME}"
	else
		printf "\n---------------------\nInstallation aborted.\n---------------------\n"
		printf "This script uses a set of system commands which may be\n"
		printf "in a different location on your system.\n\n"
		printf "The following system command was not found: /usr/bin/${CMD_NAME}\n\n"
		exit
	fi
}

#--
#-- Setup System variables which need for Katusha Software installation
#--
initialize_variables()
{
	set_variable ID_CMD id
	set_variable GREP_CMD grep
	set_variable EGREP_CMD egrep
	set_variable LS_CMD ls
	set_variable DIRNAME_CMD dirname
	set_variable BASENAME_CMD basename
	set_variable PRINTF_CMD printf
	set_variable ECHO_CMD echo
	set_variable CAT_CMD cat
	set_variable AWK_CMD awk
	set_variable SED_CMD sed
	set_variable PS_CMD ps
	set_variable CHMOD_CMD chmod
	set_variable TR_CMD tr
	set_variable ICONV_CMD iconv
	set_variable CP_CMD cp
	set_variable RM_CMD rm
}
initialize_variables
echo "Setup System variables which need for Katusha Software installation ==> [DONE]"

#--
#-- Verify that CUPS PPD Directories are on the system.
#--
check_for_cups()
{
	if [ ! -d "${CUPS_PPD_ROOT}" ];then
		${ECHO_CMD}
		${ECHO_CMD} "Error:  CUPS PPD directories were not found."
		${ECHO_CMD} "        Either CUPS is not installed or CUPS was installed"
		${ECHO_CMD} "        in a non standard directory."
		${ECHO_CMD}
		${ECHO_CMD} "        If you do have CUPS installed, just copy the PPD files"
		${ECHO_CMD} "        into your CUPS PPD directory and restart CUPS."
		${ECHO_CMD}
		exit 1
	fi
}
check_for_cups
echo "Finding CUPS PPD folders ==> [DONE]"

#--
#-- Check for root
#--
check_for_root()
{
	ID=`${ID_CMD}`
	${ECHO_CMD} "${ID}" | ${GREP_CMD} "uid=0" >/dev/null 2>&1
   if [ "${?}" != "0" ]; then
		${ECHO_CMD}
		${ECHO_CMD} "You must be a ROOT to run this program."
		${ECHO_CMD}
		exit 1
	fi
}

check_for_root

lowercase(){
    echo "$1" | sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/"
}
#####################################
# HARDWARE
#####################################
OS=`lowercase \`uname\``
ARCH=`uname -m`
KERNEL=`uname -r`

echo
echo Define your OS
echo ======================================
echo OS Type: $OS
echo OS Arch: $ARCH
if [[ -f /etc/os-release ]]; then
	. /etc/os-release
	int_OS=$NAME
	int_VER=$VERSION_ID
	echo OS Name: $int_OS
	echo OS Version: $int_VER
fi
echo Kernel: $KERNEL
echo ======================================
echo

# Reset umask for install package...
umask 002
# Determine correct echo options...
if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
	ac_n=-n
	ac_c=
else
	ac_n=
	ac_c='\c'
fi

# установка прав на папку CUPS interfaces
if [ ! -d /etc/cups/interfaces ]; then
	mkdir -p /etc/cups/interfaces
	chmod 755 /etc/cups/interfaces
	chown root:lp /etc/cups/interfaces
fi
if [ ! -d /var/spool/lpd ]; then
	mkdir -p /var/spool/lpd
	chmod 755 /var/spool/lpd
	chown lp:lp /var/spool/lpd
fi
echo "Setup CUPS interfaces access ==> [DONE]"

if test -f /usr/.writetest; then
	rm -f /usr/.writetest
fi
echo "Testing /usr/ WRITE file operations ==> [DONE]"

title="(notice) выберите из списка пакет, который хотите установить:
(warning) чтобы установить другой пакет, перезапустите Katusha Package Manager еще раз!"
prompt="(action) выберите требуемое действие:"
options=("Install Important Packages" #1
		"Katusha Universal Driver Package" #2
		"Katusha MFP Driver for P/M[130] Series" #3
		"Katusha MFP Driver for M247 Series" #3
		"Katusha MFP Driver for M348 Series" #4
         )
echo
echo +++++++++++++++++++++++++++++++++
echo Build Date: 23.10.2024\ / Katusha
echo Type: All-in-One
echo Name: Katusha UNIX Printer/Scanner Driver Package Installer
echo Version: 2.1-1-stable
echo Support: All Katusha Devices in M and P series
echo ++++++++++++++++++++++++++++++++++++++++++++++
echo
echo "$title"
PS3="$prompt "
COLUMNS=121
select opt in "${options[@]}" "Отменить"; do
    case "$REPLY" in
    1) echo "Вы выбрали $opt, ожидайте завершения установки";
		# Определение необходимости установки пакетов
		which wget
		if [[ $(echo $?) == "0" ]]; then
			echo "[wget] are installed!"
			wget -q --tries=10 --timeout=20 --spider http://google.com
			if [[ $? -eq 0 ]]; then
				echo "We are Online!"
				if [[ $(cat /etc/os-release | egrep -c "Astra|SparkyLinux|Deepin") -ge 1 ]]; then
					sudo apt update
					echo Сhecking dependencies required to run the installation script...
					NEED_PACKAGES="sane sane-utils libcupsimage2"
					for PKG in $NEED_PACKAGES
					do
						if [ $(dpkg-query -W -f='${Status}' $PKG 2>/dev/null | grep -c "ok installed") -eq 0 ];
							then
								echo Installing necessary packages...
								sudo apt-get -y install $PKG;
						fi
					done
					echo "Updating DONE"
				fi
				if [[ $(cat /etc/os-release | egrep -c "RED OS|Fedora Linux") -ge 1 ]]; then
					sudo dnf makecache
					sudo dnf install lynx
					echo "Updating DONE"
				fi
				if [[ $(cat /etc/os-release | grep -c "altlinux") -ge 1 ]]; then
					apt-get update && apt-get --fix-broken -y install
					echo Сhecking dependencies required to run the installation script...
					NEED_PACKAGES="sane sane-frontends sane-airscan simple-scan xsane"
					for PKG in $NEED_PACKAGES
					do
						rpm -qa | grep -qw $PKG || apt-get install -y $PKG
					done
					echo "Updating DONE"
				fi
				#Next Statements
			else
				echo "Please check your internet connection!"
			fi
		else
			echo "[wget] are not installed!"
			echo "please install [wget] manual or check your internet connection"
		fi
    break;;
		2) echo && echo "=== $opt ===";
		bash $RUN_KATUSHA_UNIVERSAL.task
		break;;
		3) echo && echo "=== $opt ===";
		bash $RUN_KATUSHA_M130.task
		break;;
		4) echo && echo "=== $opt ===";
		bash $RUN_KATUSHA_M247.task
		break;;
		5) echo && echo "=== $opt ===";
		bash $RUN_KATUSHA_M348.task
		break;;
    $((${#options[@]}+1))) echo "Установка была отменена";
		break;;
    *) echo "Неправильный ввод. Вы ошиблись. Повторите.";continue;;
    esac
done
