#!/bin/sh

#script informations
program="archE17svn"
author="Fabio Falcinelli"
email="fabio.falcinelli@gmail.com"
contributor="Igor Scabini"
contributor_email="furester@gmail.com"
license="GPL"
version="0.6.3"
last_modified="02.05.2009"
arch="i686"

#paths
echo ${HOME:?"Could not find '$HOME' variable!"} > /dev/null
work_dir="$HOME/$program"
abs_dir="/var/abs"
repo_dir="$work_dir/repo"
#pkgbuild_url="http://aur.archlinux.org/packages"

#ftp settings
ftp_user=""
ftp_passwd=""
ftp_host=""
ftp_dir=""

#packages
#efl_array="eina edb eet evas ecore efreet epeg embryo edje epsilon esmart emotion engrave etk ewl exml enhance e_dbus emprint exalt"
pkg_array="eina edb eet evas ecore efreet epeg embryo edje epsilon esmart emotion engrave etk etk_extra ewl exml enhance e_dbus emprint exalt e entrance edje_viewer edje_editor elicit elitaire emphasis empower ephoto estickies exhibit expedite exquisite extrackt enthrall rage scrot elementary e-modules-extra"
#modules_array="alarm bling calendar cpu deskshow emu flame forecasts language mail mem mixer moon net news penguins photo rain screenshot slideshow snow systray taskbar tclock uptime weather winselector wlan"
python_array="python-e_dbus python-ecore python-edje python-etk python-evas python-elementary"

#ensure paths are set up correctly
echo ${work_dir:?"Working directory isn't set up properly!"} > /dev/null
echo ${abs_dir:?"Arch Build System (abs) directory isn't set up properly!"} > /dev/null

#global settings
#by default do not create e17 repo
create_repo="false"
force_rebuild="false"

function logInfo()
{
	msg="`date` [INFO] - $@"	
	log $msg
}

function logError()
{
	msg="`date` [ERROR] - $@"	
	log $msg
	echo $@ &> /dev/null >> ${work_dir}/error.log 
}

# save log in a file for further reading
function log()
{
	echo $@
	echo $@ &> /dev/null >> ${work_dir}/events.log 
}

#check if a parameter is in environment variable PATH
function checkInPath()
{
	which $1 > /dev/null
	if [[ $? -ne 0 ]] ; then
		logError "Cannot find $1 in PATH ($PATH)"
		return 1
	fi
	logInfo "$1 found" 
	return 0
}

#build and install pkguild from enlightenment svn tree
function buildAndInstall()
{	
	for pkg in $@ ; do
		pkg_name="$pkg-svn"
		
			dest_dir=$work_dir/$pkg_name
			
			free_mem_left=`df -h ${work_dir} | grep /dev | awk '{print $4}'`
			logInfo "${free_mem_left}b left"
			# 100Mb isn't minimum requirement but a temporary value
			if [[ `df ${work_dir} | grep /dev | awk '{ if ( 10000 > $4) { print "low_mem"} }'` == "low_mem" ]]; then
				logError "Almost no space left on device. Exiting."
				exit 1;
			fi
			
			if [[ -e $dest_dir ]] ; then
				logInfo "Directory $dest_dir already exists"
				cd $dest_dir
				if [[ -e "$dest_dir/old" ]] ; then
					logInfo "Copying backup packages in old  dir"
				else
					logInfo "Creating old directory for backups"
					mkdir -p "$dest_dir/old"
				fi
				mv $pkg_name*.tar.gz $dest_dir/old
			else
				logInfo "Creating directory $dest_dir"
				mkdir -p $dest_dir
			fi

		pkg_dir=`find $abs_dir/community -name $pkg_name | grep -v pkg`
		if [[ $pkg_dir != "" ]] ; then	
			logInfo "$pkg_name found in ABS"
			logInfo "Moving contents to $dest_dir"
			cp -r $pkg_dir/* $dest_dir		
			cd $dest_dir			
		else
			logInfo "$pkg_name not found in ABS"
#			logInfo "Trying a run on AUR with yaourt"
#			yaourt -S --noconfirm $pkg_name
			logInfo "Trying to download from AUR with yaourt"
			cd $dest_dir
			if [[ -e PKGBUILD ]] ; then
				logInfo "Removing old PKGBUILD"
				rm PKGBUILD
			fi
			yaourt -G $pkg_name --noconfirm
		fi
	
		count=0
		if [[ -e src && $force_rebuild == "false" ]] ; then
			svntrunk=`grep "svntrunk" PKGBUILD | grep $pkg | cut -f2 -d "=" | sed 's/\"//g'`			
			logInfo "Using trunk $svntrunk"			
			cd src
			count=`svn co $svntrunk | grep -c ""`
			cd $dest_dir
		fi
		
		if [[ $count -eq 1 ]] ; then
			#1 row implies no changes -> no install at all
			logInfo "No changes to $pkg_name sources"
			#check if is installed
			installed=`pacman -Qq $pkg_name`
			if [[ $installed != $pkg_name ]] ; then
				logInfo "$pkg_name is not installed! Reinstalling"
				#by default makepkg will not build a pkg if already exists
				# a built one				
				makepkg -iseL || logError "$pkg_name build failed"
			else
				logInfo "Nothing to be done for $pkg_name"
			fi

		elif [[ $count -eq 0 ]] ; then
			#No row means no svn co performed so no src then new pkg
			logInfo "$pkg_name is new"
			makepkg -isL || logError "$pkg_name build failed"
		else
			#Any other number means some files has been changed
			#src has been already updated by svn process, reusing src
			logInfo "$pkg_name has been changed"
			#BUG: sources must be cleaned up!
			rm -fr src pkg
			#makepkg -iseL || logError "$pkg_name build failed"
			makepkg -isL || logError "$pkg_name build failed"
		fi

		if [[ $create_repo == "true" ]] ; then
			add2repo $pkg_name*.tar.gz
		fi
	done
}

#reverts the installation to the pre-compiled packages on
#archlinux community repository
function revert2Snapshot()
{
	logInfo "Reinstalling community snapshot"
	for pkg in $pkg_array ; do
		yaourt -S "$pkg-svn" --noconfirm
	done 
#	logInfo "Modules"
	return 0
}

#TODO: send the repo to an ftp server
function send2FTPServer()
{
	ftp
}

#TODO: add package to e17 repo with repo-add
function add2Repo
{
	checkInPath repo-add
	logInfo "Adding $@ to repository e17.db.tar.gz in $repo_dir"
	repo-add $work_dir/e17.db.tar.gz $@ && logInfo "Done"
}

function compilePkgs()
{
	#check for commands in $PATH
	checkInPath abs || exit 1;
	checkInPath makepkg || exit 1;

	# check if $user can launch abs with sudo
	SUDOINSTALLED=0
	command=`echo "abs" | awk '{gsub(/LC_ALL=\"C\"/,""); print $1}'`
	if [ `type -p sudo` ]; then SUDOINSTALLED=1; fi
	sudo -l | sed 's/\,/\n/g' | grep "\(\ $command$\|ALL\)"
	if [ $SUDOINSTALLED -eq 1 ] && sudo -l | sed 's/\,/\n/g' | grep "\(\ `which $command`$\|ALL\)" 1>/dev/null; then
		logInfo "ABS Synchronizing"
		sudo $command
	fi


#	logInfo "ABS Synchronizing"
#	sudo abs

	logInfo "Build and install"

	#build and install the base libs
	buildAndInstall $pkg_array

#these won't work without $only variable
#	if [[ -z "$only" ]]; then
#		logInfo "Modules"
#		#build and install the modules
#		buildAndInstall "e-modules-extra" 
#	fi
	logInfo "Done"
	
	return 0;
}

function showHelp()
{
	echo >&2 "Usage: $0 [-hdRrf] [-o <list>] [-w <dir>]"
	echo >&2 "Available options:"
	echo >&2 "   -r create e17 repo (experimental)"
	echo >&2 "   -f force rebuild of packages"
	echo >&2 "   -R revert to latest community snapshot"
	echo >&2 "   -d compile with CFLAGS=-g"
	echo >&2 "   -o=<name1>,<name2>,... checkout and compile ONLY the named libs/apps"
	echo >&2 "   -w=<dir> change working directory (default $work_dir)"
	echo >&2 "   -h print this help message"
}

function main()
{
	options=""

	if [ -e "$HOME/.${program}.conf" ]; then
		# load configfile 
		for option in `cat "$HOME/.${program}.conf"`
		do
			options="$options $option"
		done
	fi

	# append arguments
	options="$options $@"

	# check options
	for arg in $options
	do
		option=`echo "'$arg'" | cut -f'-1' -d"=" | tr -d "'"`
		value=`echo "'$arg'" | cut -f'2-' -d"=" | tr -d "'"`
		if [ "$value" == "$option" ]; then
			value=""
		fi

		case "$option" in
			"-h"|"--help")		showHelp;
						exit 0
						;;
			"-d"|"--debug")		export CFLAGS="${CFLAGS} -g" ;;
			"-R"|"--revert")	revert2Snapshot ;
						exit $?
						;;
			"-r") 			create_repo="true" ;;
			"-f"|"--force")		force_rebuild="true" ;;	
			"-o"|"--only")		pkg_array="`echo "$value" | cut -f'1-' -d"," --output-delimiter=" " `"; 
						logInfo "Building only: $pkg_array" 
						;;
			"-w")			work_dir="${value}/$program" ; 
						logInfo "Using $work_dir as working directory" 
						;;
			*)			showHelp ;
						logError "$option invalid option"
						exit 1
						;;
		esac
	done

	logInfo "ARCHLINUX E17 SVN"
	logInfo "$program $version $last_modified"
	logInfo "(C) 2009 $author $email"
	logInfo "$contributor $contributor_email"
	logInfo "Released under $license license"

	checkInPath sudo || exit 1;
#	checkInPath pacman || exit 1;
	checkInPath yaourt || exit 1;
	repo_dir="$work_dir/repo"
	mkdir -p ${work_dir}
	mkdir -p ${repo_dir}

	compilePkgs
	exit $?
}

main $@

