#!/bin/sh
# Glacier package checker

INSCRIPT=INSTALL.sh
UPSCRIPT=UPDATE.sh
RMSCRIPT=REMOVE.sh

PKGINFO=*-pkginfo.json

TIMESTAMP=*.ts.sh

check_dir() {
	printf "Searching for package directory...\n"
		if [ -d "$2" ]; then
			printf "${green}$2 exists.${reset}\n"
		else
			printf "${red}$2 does not exist.${reset}\n"
			exit 1
		fi

	cd $2
	printf "Searching for instruction scripts...\n"
		if [ -f $INSCRIPT -a -f $UPSCRIPT -a -f $RMSCRIPT ]; then
			printf "${green}Instruction scripts exist.${reset}\n"
		else
			printf "${red}Instruction scripts do not exist.${reset}\n"
			exit 1
		fi

	printf "Searching for miscellaneous files...\n"
		if [ -f $PKGINFO -a -f $TIMESTAMP ]; then
			printf "${green}$2-pkginfo.json and $2.ts.sh exist.${reset}\n"
		else
			printf "${red}$2-pkginfo.json and $2.ts.sh do not exist.${reset}\n"
			exit 1
		fi
}

mkpkg() {
	printf "${blue} Making package...${reset}\n"
		cd $2
		tar -czvf $2.tar.gz *
	printf "${blue}Generating package checksum...${reset}\n"
		cd ..
		sha256sum $2/$2.tar.gz >> $2.checksum
	printf "${green}Finished making package${reset}\n"
	exit 0
}

helpmsg() {
	printf "gpc - test and create Glacier compatible packages\n"
	printf "usage: gpc [check] [mkpkg] [-h/--help] [-v/--version] pkg-dir\n"
	printf "\n"
	printf "gpc {-h|--help}		show this message and exit\n"
	printf "gpc {-v|--version}	show the version and exit\n"
	printf "gpc {check}		check a package directory for compliance\n"
	printf "gpc {mkpkg}		create a package from a directory\n"
	printf "\n"
	printf "This program is free software.\n"
	printf "See the GNU GPL version 3 for details.\n"
	exit 0
}

helpmsg_small() {
	printf "usage: gpc [check] [mkpkg] [-h/--help] [-v/--version] pkg-dir\n"
	exit 1
}

printver() {
	printf "gpc v2.0.0\n"
	exit 0
}

preload() {
	. $(pwd)/gpc.conf
		if [ "$?" != "0" ]; then
			printf "error while parsing gpc config file\n"
			exit 1
		fi
}

case $1 in
	-h|--help)
		helpmsg "$@"
	;;
	-v|--version)
		printver "$@"
	;;
	check)
		check_dir "$@"
	;;
	mkpkg)
		mkpkg "$@"
	;;
	*)
		helpmsg_small "$@"
	;;
esac 
