#!/bin/bash

#export TSUDO="$HOME/.package-manager/builtin-scripts/tsudo.sh"
#export INSTALLMANAGER_UI=GUI
#export INTERACTIVE=true
SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
flag=0

declare -a debs=("libicu60_60.2-3ubuntu3.1_amd64.deb" "libjavascriptcoregtk-1.0-0_2.4.11-3ubuntu3_amd64.deb" "libwebkitgtk-1.0-0_2.4.11-3ubuntu3_amd64.deb")

#Ubuntu 22 deb packages
declare -a debs_22=("libwebp6_0.6.1-2ubuntu0.20.04.1_amd64.deb" "libenchant1c2a_1.6.0-11.3build1_amd64.deb" "libegl1-mesa_22.0.1-1ubuntu2_amd64.deb" "libgdk-pixbuf-xlib-2.0-0_2.40.2-2build4_amd64.deb" "libgdk-pixbuf2.0-0_2.40.2-2_amd64.deb")

#Ubuntu 22 package names
declare -a pkgs_22=("libwebp6" "libenchant1c2a" "libegl1-mesa" "libgdk-pixbuf-xlib-2.0-0" "libgdk-pixbuf2.0-0")

declare -a pkgs=("libicu60" "libjavascriptcoregtk-1.0-0" "libwebkitgtk-1.0-0")

length=${#debs[@]}
echo "Checking: ${pkgs[$length - 1]}"
isInstalled=`dpkg -l ${pkgs[$length - 1]} | grep ^ii`
if [[ $isInstalled != "" ]]; then
	echo "${pkgs[$length - 1]} is already installed. Exiting with status 1"
	exit $flag;
fi

var=$(lsb_release -r)
ubuntu_ver=$(cut -f2 <<< "$var")
if [[ $ubuntu_ver == "22.04" ]]; then
	length_22=${#debs_22[@]}
	for (( i=0; i<${length_22}; i++ ));
	do
		echo "Checking: ${pkgs_22[$i]}"
		isInstalled=`dpkg -l ${pkgs_22[$i]} | grep ^ii`
		if [[ $isInstalled == "" ]]; then
			"$TSUDO" apt -y install "$SCRIPTPATH/${debs_22[$i]}"
			status=$?
			if [ "$status" == 1 ]; then 
				echo "failed to install: ${pkgs_22[$i]}. Please try to manually install: $SCRIPTPATH/${debs_22[$i]}"
				flag=1
			fi
		else
			echo "${pkgs_22[$i]} is already installed"
		fi	
	done
fi

for (( i=0; i<${length}; i++ ));
do
	echo "Checking: ${pkgs[$i]}"
	isInstalled=`dpkg -l ${pkgs[$i]} | grep ^ii`
	if [[ $isInstalled == "" ]]; then
		"$TSUDO" apt -y install "$SCRIPTPATH/${debs[$i]}"
		status=$?
		if [ "$status" == 1 ]; then 
			echo "failed to install: ${pkgs[$i]}. Please try to manually install: $SCRIPTPATH/${debs[$i]}"
			flag=1
		fi
	else
		echo "${pkgs[$i]} is already installed"
	fi
		
done

exit $flag;
