#!/bin/bash
proj=aramis
reqs="xargs awk git sed tar sort head cut dirname"
count=$(echo $reqs | awk '{printf NF}')
iter=$((count+1))
while [ "$iter" != "$((count+1))" ]
do
	req=$(echo $reqs | cut -d " " -f $iter)
	if ! which $req 2>&1 1>/dev/null
	then
		echo "Dependency not found: $req"
		exit 1
	fi
	iter=$((iter+1))
done

if [ "$1" == "" ] || [ "$1" == "help" ] || [ "$1" == "--help" ]
then
	echo "Usage: $proj [install|uninstall|list]"
	exit 0
elif [ "$1" == "list" ]
then
	if [ ! -d /opt/aramis/* ]
	then
		echo "No packages installed."
	else
		find /opt/aramis/ -maxdepth 2 | sed 's/\/opt\/aramis\///' | grep '/' | sed 's/\//\t\t/'
	fi
elif [ "$1" == "install" ] || [ "$1" == "--install" ]
then
	set -e
	if [ "$(echo $2 | xargs)" == "" ]
	then
		echo "Usage: $proj [tar file]"
		exit 0
	fi
	file=$(tar -tf $2 2>/dev/null | awk '{print length($0) "\t" $0}' | sort -nr | head -1 | cut -f2-)
	if [ "$file" == "" ]
	then
		echo "Error: Could not read file."
		exit 1
	fi
	name=$(echo $file | cut -d "/" -f 3)
	vers=$(echo $file | cut -d "/" -f 4)
	if [ -d /opt/$proj/$name/$vers ]
	then
		echo "Error: Package already installed."
		exit 1
	fi
	others=$(ls /opt/$proj/$name/ 2>/dev/null | xargs)
	count=$(echo $others | awk '{printf NF}')
	if [ "$count" != "0" ]
	then
		echo "Warning: There exists other versions"
		iter=1
		while [ "$iter" != "$((count+1))" ]
		do
			ver=$(echo $others | cut -d " " -f $iter)
			echo -e "\t$name\t$ver"
			iter=$((iter+1))
		done
		read -p "Proceed anyway? " ans
		if [ "$ans" != "Y" ] && [ "$ans" != "y" ]
		then
			exit 0
		fi
	fi
	tar -xf $2 -C /
	tar -tf $2 | awk '{print length($0) "\t" $0}' | sort -nr | cut -f2- | xargs > /opt/$proj/$name/$vers/.list
	echo -e "Installed: $name $vers"
elif [ "$1" == "uninstall" ] || [ "$1" == "--uninstall" ] || [ "$1" == "remove" ] || [ "$1" == "--remove" ]
then
	set -e
	if [ "$(echo $2 | xargs)" == "" ]
	then
		echo "Usage: $proj [name]"
		echo "Usage: $proj [name] [version]"
		exit 0
	fi
	name=$2
	vers=$3
	if [ "$(echo $vers | xargs)" == "" ]
	then
		vers="*"
	fi
	if [ ! -d /opt/$proj/$name/$vers ]
	then
		echo "Error: Package is not installed."
		exit 1
	fi
	lists=$(ls /opt/$proj/$name/$vers/.list 2>/dev/null | xargs)
	count=$(echo "$lists" | awk '{printf NF}')
	iter=1
	while [ "$iter" != "$((count+1))" ]
	do
		list=$(echo $lists | cut -d " " -f $iter)
		files=$(cat $list)
		rm -rf 2>/dev/null $(dirname $list)
		count2=$(echo $files | awk '{printf NF}')
		iter2=1
		while [ "$iter2" != "$((count2+1))" ]
		do
			file=$(echo $files | cut -d " " -f $iter2)
			if [ "$file" != "" ]
			then
				set +e
				rm -d /$file 2>/dev/null
				set -e
			fi
			iter2=$((iter2+1))
		done
		iter=$((iter+1))
	done
	echo -e "Removed: $name $vers"
else
	echo "Usage: $proj [install|uninstall|list]"
fi
