#!/bin/sh
# Glacier - manage installed packages on a Linux system
#
# This file is part of Glacier.
#
# Glacier is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
#
# Glacier is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with Glacier. If not, see <https://www.gnu.org/licenses/>. 

source /etc/glacier/hooks

get_pkg() {
	printf "$blue[ i ]$reset Downloading archive for package '$2'...\n"
		$GLACIER_DOWNLOAD_BACKEND $GREPO1/$2.tar.gz || $GLACIER_DOWNLOAD_BACKEND $GREPO2/$2.tar.gz || $GLACIER_DOWNLOAD_BACKEND $GREPO3/$2.tar.gz || $GLACIER_DOWNLOAD_BACKEND $GREPO4/$2.tar.gz || $GLACIER_DOWNLOAD_BACKEND $GREPO5/$2.tar.gz || $GLACIER_DOWNLOAD_BACKEND $GREPO6/$2.tar.gz || $GLACIER_DOWNLOAD_BACKEND $GREPO7/$2.tar.gz || $GLACIER_DOWNLOAD_BACKEND $GREPO8/$2.tar.gz
			if [ "$?" != "0" ]; then
				printf "$red[ $error ]$reset Package '$2' not found.\n"
				exit 1
			fi
		$GLACIER_DOWNLOAD_BACKEND $GREPO1/$2.checksum || $GLACIER_DOWNLOAD_BACKEND $GREPO2/$2.checksum || $GLACIER_DOWNLOAD_BACKEND $GREPO3/$2.checksum || $GLACIER_DOWNLOAD_BACKEND $GREPO4/$2.checksum || $GLACIER_DOWNLOAD_BACKEND $GREPO5/$2.checksum || $GLACIER_DOWNLOAD_BACKEND $GREPO6/$2.checksum || $GLACIER_DOWNLOAD_BACKEND $GREPO7/$2.checksum || $GLACIER_DOWNLOAD_BACKEND $GREPO8/$2.tar.gz
			if [ "$?" != "0" ]; then
				printf "$red[ $error ]$reset Package checksum not found.\n"
				exit 1
			fi
}

int_check() {
	if [ "$GLACIER_DO_INT_CHECK" = "true" ]; then
		printf "$blue[ i ]$reset Checking package integrity...\n"
			mv *.checksum local_sum
			sha256sum *.tar.gz > pkg_sum
			/usr/bin/glacier-integrity-check local_sum pkg_sum
				if [ "$?" != "0" ]; then
					printf "$red[ $error ]$reset Integrity check failed.\n"
					exit 1
				fi
		printf "$green[ $check ]$reset Integrity check passed.\n"
	else
		printf "$yellow[ ! ]$reset Skipping integrity check...\n"
	fi
}

unpack_pkg() {
	printf "$blue[ i ]$reset Unpacking $2.tar.gz...\n"
	mkdir $2 && mv $2.tar.gz $2 && cd $2
	tar -xf $2.tar.gz
		if [ "$?" != "0" ]; then
			printf "$red[ $error ]$reset Could not unpack $2.tar.gz.\n"
			cd .. && rm -rf $2
			exit 1
		fi
}

installpkg() {
	printf "$blue[ i ]$reset Installing $2...\n"
		sleep 1
		chmod +x *
		./INSTALL.sh
			if [ "$?" != "0" ]; then
				printf "$red[ $error ]$reset Failed to update $2.\n"
				cd .. && rm -rf $2
				exit 1
			fi
		./$2.ts.sh
		mv $2-pkginfo.json /etc/glacier/pkginfo
}

updatepkg() {
	printf "$blue[ i ]$reset Updating $2...\n"
		sleep 1
		chmod +x *
		./UPDATE.sh
			if [ "$?" != "0" ]; then
				printf "$red[ $error ]$reset Failed to update $2.\n"
				cd .. && rm -rf $2
				exit 1
			fi
		./$2.ts.sh
}

removepkg() {
	printf "$blue[ i ]$reset Removing $2...\n"
		sleep 1
		chmod +x *
		/etc/glacier/pkginfo/$2.remove
			if [ "$?" != "0" ]; then
				printf "$red[ $error ]$reset Failed to remove $2.\n"
				cd .. && rm -rf $2
				exit 1
			fi
		rm /var/log/glacier/$2.timestamp
		rm /etc/glacier/pkginfo/$2-pkginfo.json
}

installpkg_from_cache() {
	printf "$blue[ i ]$reset Installing $2 from cache...\n"
		sleep 1
		cd /var/cache/glacier && cp $2.tar.gz /tmp && cd /tmp
			if [ "$?" != "0" ]; then
				printf "$red[ $error ]$reset Package does not exist in cache.\n"
				exit 1
			fi
		unpack_pkg
		install_pkg
}

clear_cache() {
	printf "$blue[ i ]$reset Clearing cache...\n"
		sleep 1
		cd /var/cache/glacier && rm -rvf *
			if [ "$?" != "0" ]; then
				printf "$red[ $error ]$reset Some items could not be cleared.\n"
				exit 1
			fi
}

#
# Show Glacier debugging info
#

debug_info() {
	printf "$blue>> Glacier v3.2.1$reset\n"
	printf ">> Checking for valid download backend...\n"
		whereis wget
		whereis curl
		whereis aria2c
	printf ">> Checking which download backend is in use...\n"
		echo $GLACIER_DOWNLOAD_BACKEND
	printf ">> Checking if all Glacier files are present...\n"
		whereis glacier glacier.conf make.conf
		ls /var/log | grep glacier
		ls /var/cache | grep glacier
	printf ">> If any files are missing, Glacier will not behave properly.\n"
	printf ">> Checking if terminal can output unicode symbols...\n"
		printf "$check\n"
		printf "$error\n"
		printf "$warning\n"
		printf "$question\n"
		printf "$red Red.$reset\n"
		printf "$green Green.$reset\n"
		printf "$yellow Yellow.$reset\n"
		printf "$blue Blue.$reset\n"
	printf "NOTE: If you use a custom colorscheme, colors will not match.\n"
	printf ">> Checking if repositories are valid...\n"
		echo $GREPO1
		echo $GREPO2
		echo $GREPO3
		echo $GREPO4
		echo $GREPO5
		echo $GREPO6
		echo $GREPO7
		echo $GREPO8
	printf ">> Checking which shell is in use...\n"
		which $SHELL
	printf "NOTE: If you use zsh, a percentage symbol may appear after some lines.\n"
	printf ">> Gathered debug information.\n"
	printf ">> To save this information to a file, run:\n"
	printf ">> $ glacier --debuginfo > glacier.debug\n"
}

#
# Parses JSON from pkginfo files and outputs it
#

query() {
	printf "$blue[ i ]$reset Showing information for package '$2'.\n"
	printf "$blue>> Package name:$reset " && cat /etc/glacier/pkginfo/$2-pkginfo.json | jq .package_name
	printf "$blue>> Package version:$reset " && cat /etc/glacier/pkginfo/$2-pkginfo.json | jq .package_version
	printf "$blue>> Package description:$reset " && cat /etc/glacier/pkginfo/$2-pkginfo.json | jq .package_description
	printf "$blue>> Source tree size:$reset " && cat /etc/glacier/pkginfo/$2-pkginfo.json | jq .src_tree_size
	printf "$blue>> Size of installed files:$reset " && cat /etc/glacier/pkginfo/$2-pkginfo.json | jq .exec_size
	printf "$blue>> License:$reset " && cat /etc/glacier/pkginfo/$2-pkginfo.json | jq .license
	printf "$blue>> Installation date:$reset " && cat /var/log/glacier/$2.timestamp
}

#
# Will either keep removal script, update it with a new one, or delete it alltogether
#

cleanup_keep_rm () {
	printf "$blue[ i ]$reset Cleaning up...\n"
	mv REMOVE.sh /etc/glacier/pkginfo/$2.remove
	cd .. && rm -rf *.checksum *.tar.* $2
}

cleanup_update_rm () {
	printf "$blue[ i ]$reset Cleaning up...\n"
	rm /etc/glacier/pkginfo/$2.remove
	mv REMOVE.sh /etc/glacier/pkginfo/$2.remove
	cd .. && rm -rf *.checksum *.tar.* $2
}

cleanup_del_rm () {
	printf "$blue[ i ]$reset Cleaning up...\n"
	rm /etc/glacier/pkginfo/$2.remove
	cd .. && rm -rf *.checksum *.tar.* $2
}

#
# Execute pre and posr hooks from files
#

pre_hooks() {
	source /etc/glacier/hooks
}

pre_op_hooks() {
	printf "$blue[ i ]$reset Executing pre-operation hooks...\n"
	/etc/glacier/pre-hooks
}

post_hooks () {
	printf "$blue[ i ]$reset Executing post-operation hooks...\n"
	/etc/glacier/post-hooks
}

case $1 in
	-h|--help)
		printf "$blue[ * ] Glacier - Manage installed packages on the system$reset\n"
		printf "usage: glacier [-f] [-u] [-x] [-q] [-c] [-ci] [-cc] [--debuginfo]\n"
		printf "\n"
		printf "$blue=== Information ===$reset\n"
		printf "glacier {-h/--help} - Show this message and exit\n"
		printf "glacier {-v/--version} - Show the version and exit\n"
		printf "\n"
		printf "$blue=== Operations ===$reset\n"
		printf "glacier {-f/install} - Install a new package\n"
		printf "glacier {-u/update} - Update an installed package\n"
		printf "glacier {-x/remove} - Remove an installed package\n"
		printf "glacier {-q/query} - Query an installed package\n"
		printf "glacier {-c/cache} - Download a package to the cache\n"
		printf "glacier {-ci/cache-install} - Install a package from the cache\n"
		printf "glacier {-cc/cache-clear} - Clear the cache\n"
		printf "\n"
		printf "$blue=== Debugging ===$reset\n"
		printf "glacier {--debuginfo} - Show debugging information\n"
		printf "\n"
		printf "$blue=== Licensing ===$reset\n"
		printf "This program is free software: you can redistribute it and/or modify it\n"
		printf "under the terms of the GNU General Public License as published by the\n"
		printf "Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n"
		exit 0
	;;
	-v|--version)
		printf "${blue}Glacier v3.2.1${reset}\n"
		exit 0
	;;
	-f|install)
		if [[ $(/usr/bin/id -u) -ne 0 ]]; then
			printf "$red[ $error ]$reset Please run Glacier as root.\n"
			exit 1
		fi
		
		if [ "$2" == "" ]; then
			printf "$red[ $error ]$reset No package name was supplied.\n"
			exit 1
		fi

		printf "$blue[ i ]$reset Installing package '$2'.\n"
		read -p "$(printf "$blue[ ? ]$reset Proceed with this operation? (y/n) ")" -n 1 -r
			if [[ $REPLY =~ ^[Yy]$ ]]; then
				cd /opt/glacier/workspace
				printf "\n"
				pre_hooks "$@"
				get_pkg "$@"
				int_check "$@"
				unpack_pkg "$@"
				pre_op_hooks "$@"
				installpkg "$@"
				post_hooks "$@"
				cleanup_keep_rm "$@"
				printf "$green[ $check ]$reset Operation completed.\n"
				exit 0
			elif [[ $REPLY =~ ^[Nn]$ ]]; then
				printf "\n"
				printf "${red}[ $error ]${reset} Aborting.\n"
				exit 1
			fi
	;;
	-u|update)
		if [[ $(/usr/bin/id -u) -ne 0 ]]; then
			printf "$red[ $error ]$reset Please run Glacier as root.\n"
			exit 1
		fi
		
		if [ "$2" == "" ]; then
			printf "$red[ $error ]$reset No package name was supplied.\n"
			exit 1
		fi

		printf "$blue[ i ]$reset Updating package '$2'.\n"
		read -p "$(printf "$blue[ ? ]$reset Proceed with this operation? (y/n) ")" -n 1 -r
			if [[ $REPLY =~ ^[Yy]$ ]]; then
				cd /opt/glacier/workspace
				printf "\n"
				pre_hooks "$@"
				get_pkg "$@"
				int_check "$@"
				unpack_pkg "$@"
				pre_op_hooks "$@"
				updatepkg "$@"
				post_hooks "$@"
				cleanup_update_rm "$@"
				printf "$green[ $check ]$reset Operation completed.\n"
				exit 0
			elif [[ $REPLY =~ ^[Nn]$ ]]; then
				printf "\n"
				printf "${red}[ $error ]${reset} Aborting.\n"
				exit 1
			fi
	;;
	-x|remove)
		if [[ $(/usr/bin/id -u) -ne 0 ]]; then
			printf "$red[ $error ]$reset Please run Glacier as root.\n"
			exit 1
		fi

		if [ "$2" == "" ]; then
			printf "$red[ $error ]$reset No package name was supplied.\n"
			exit 1
		fi

		printf "$blue[ i ]$reset Removing package '$2'.\n"
		read -p "$(printf "$blue[ ? ]$reset Proceed with this operation? (y/n) ")" -n 1 -r
			if [[ $REPLY =~ ^[Yy]$ ]]; then
				cd /opt/glacier/workspace
				printf "\n"
				pre_hooks "$@"
				removepkg "$@"
				post_hooks "$@"
				cleanup_del_rm "$@"
				printf "$green[ $check ]$reset Operation completed.\n"
				exit 0
			elif [[ $REPLY =~ ^[Nn]$ ]]; then
				printf "\n"
				printf "${red}[ $error ]${reset} Aborting.\n"
				exit 1
			fi
	;;
	-q|query)
		if [ "$2" == "" ]; then
			printf "$red[ $error ]$reset No package name was supplied.\n"
			exit 1
		fi

		query "$@"
		exit 0
	;;
	-c|cache)
		if [[ $(/usr/bin/id -u) -ne 0 ]]; then
			printf "$red[ $error ]$reset Please run Glacier as root.\n"
			exit 1
		fi

		if [ "$2" == "" ]; then
			printf "$red[ $error ]$reset No package name was supplied.\n"
			exit 1
		fi

		printf "$blue[ i ]$reset Caching package '$2'.\n"
		read -p "$(printf "$blue[ ? ]$reset Proceed with this operation? (y/n) ")" -n 1 -r
			if [[ $REPLY =~ ^[Yy]$ ]]; then
				cd /var/cache/glacier
				printf "\n"
				get_pkg "$@"
				int_check "$@"
				printf "$green[ $check ]$reset Operation completed.\n"
				exit 0
			elif [[ $REPLY =~ ^[Nn]$ ]]; then
				printf "\n"
				printf "${red}[ $error ]${reset} Aborting.\n"
				exit 1
			fi
	;;
	-ci|cache-install)
		if [[ $(/usr/bin/id -u) -ne 0 ]]; then
			printf "$red[ $error ]$reset Please run Glacier as root.\n"
			exit 1
		fi

		if [ "$2" == "" ]; then
			printf "$red[ $error ]$reset No package name was supplied.\n"
			exit 1
		fi

		printf "$blue[ i ]$reset Installing package '$2' from cache.\n"
		read -p "$(printf "$blue[ ? ]$reset Proceed with this operation? (y/n) ")" -n 1 -r
			if [[ $REPLY =~ ^[Yy]$ ]]; then
				cd /var/cache/glacier
				mv $2.tar.gz /opt/glacier/workspace
				cd /opt/glacier/workspace
				printf "\n"
				pre_hooks "$@"
				unpack_pkg "$@"
				pre_op_hooks "$@"
				installpkg "$@"
				post_hooks "$@"
				cleanup_keep_rm "$@"
				printf "$green[ $check ]$reset Operation completed.\n"
				exit 0
			elif [[ $REPLY =~ ^[Nn]$ ]]; then
				printf "\n"
				printf "${red}[ $error ]${reset} Aborting.\n"
				exit 1
			fi
	;;
	-cc|cache-clear)
		if [[ $(/usr/bin/id -u) -ne 0 ]]; then
			printf "$red[ $error ]$reset Please run Glacier as root.\n"
			exit 1
		fi

		clear_cache "$@"
		printf "$green[ $check ]$reset Operation completed.\n"
		exit 0
	;;
	--debuginfo)
		debug_info "$@"
		exit 0
	;;
	-*|--*)
		printf "$red[ $error ]$reset Unknown option, see 'glacier -h' for usage.\n"
		exit 1
	;;
	*)
		printf "$red[ $error ]$reset Unknown option, see 'glacier -h' for usage.\n"
		exit 1
	;;
esac

printf "$red[ $error ]$reset Unknown option, see 'glacier -h' for usage.\n"
exit 1
