#!/bin/sh
#
# Tazdev - SliTaz developers and build host tool. System wide config
# file is located at: /etc/slitaz/tazdev.conf
#
# (c) 2011 SliTaz GNU/Linux - GNU gpl v3
#
# AUTHORS
#     Christophe Lincoln <pankso@slitaz.org>
#     Pascal Bellard <bellard@slitaz.org>
#

if [ -f /etc/slitaz/tazdev.conf ]; then
	CONFIG=/etc/slitaz/tazdev.conf
else [ -f $PWD/tazdev.conf ]
	CONFIG=$PWD/tazdev.conf
fi
if ! [ "$CONFIG" ]; then
	echo -e "\nNo config file found in /etc/slitaz or the current dir...\n"
	exit 0
else
	. $CONFIG
fi

usage()
{
	echo -e "\nSliTaz developers and build host tool\n
\033[1mUsage: \033[0m `basename $0` [command] [user] [stable|cooking|undigest|path]
\033[1mCommands: \033[0m\n
 usage               Print this short usage and command list
 projects-stats|-ps  Display statistics about your projects
 cmplog              Log 'tazwok cmp' result (or use tazbb)
 update-wok          Update Hg wok and copy it to the chroot wok
 chroot              Mount virtual fs if needed and chroot into the build env
 gen-chroot          Generate a chroot using the last cooking base rootfs
 clean-chroot        Clean a chroot environment (skip root/ and home/)
 purge               Remove obsolete packages and obsolete source tarballs
 dry-purge           Show obsolete packages and obsolete source tarballs
 push|-p             Upload new packages to the main mirror.
 dry-push|-dp        Show what will be uploaded to the mirror. Does nothing
 pull                Download new packages from the main mirror.
 dry-pull            Show what will be downloaded from the mirror. Does nothing
 relpkg|-rp          Archive and upload new package/project version
 reliso|-ri          Create all main flavors (not loram)\n"
}

# Exit if user is not root.
check_root()
{
	if test $(id -u) != 0 ; then
	   echo -e "\nThis program requires being run as root.\n"
	   exit 0
	fi
}

status()
{
	local CHECK=$?
	echo -en "\033[70G"
	if [ $CHECK = 0 ]; then
		echo "Done"
	else
		echo "Failed"
	fi
	return $CHECK
}

get_version()
{
	if [ "$2" = "stable" ]; then
		VERSION=stable
		SLITAZ=$STABLE
	elif [ -n "$2" ]; then
		# Undigest - custom ?
		VERSION=$2
		SLITAZ=/home/slitaz/$2
	else
		VERSION=cooking
		SLITAZ=$COOKING
	fi
	ROOTFS=$SLITAZ/chroot
	HG_WOK=$SLITAZ/wok
	BUILD_WOK=$SLITAZ/chroot/home/slitaz/wok
}

check_mirror()
{
	# ping -c 1 $MIRROR
	if [ -n "$2" ]; then
		USER=$2
	else
		USER=$USER
	fi
	if [ "$2" = "stable" ] || [ "$3" = "stable" ]; then
		REMOTE_DIR=$MIRROR_PKGS/stable/
		LOCAL_DIR=$STABLE/packages/
	elif [ "$2" = "undigest" ] || [ "$3" = "undigest" ]; then
		REMOTE_DIR=$MIRROR_PKGS/undigest/
		LOCAL_DIR=$UNDIGEST/packages/
	else
		REMOTE_DIR=$MIRROR_PKGS/cooking/
		LOCAL_DIR=$COOKING/packages/
	fi
}

# Mount virtual Kernel file systems and chroot but check that nobody
# else has done mounts
mount_chroot()
{
	if [ ! -d $ROOTFS/proc/1 ]; then
		echo -n "Mounting virtual filesystems..."
		mount -t proc proc $ROOTFS/proc
		mount -t sysfs sysfs $ROOTFS/sys
		mount -t devpts devpts $ROOTFS/dev/pts
		mount -t tmpfs shm $ROOTFS/dev/shm
		status
	fi
}

# Unmount virtual Kernel file systems on exit and ensure we are the last
# user before unmounting !
umount_chroot()
{
	# Not working. Buggy ps ?
	#sleep 6
	ps=$(ps | grep `basename $0` | grep -v grep | wc -l)
	if [ "$ps" == "1" ]; then
		echo -ne "\Unmounting virtual filesystems..."
		umount $ROOTFS/dev/shm
		umount $ROOTFS/dev/pts
		umount $ROOTFS/sys
		umount $ROOTFS/proc
		status
	else
		echo -e "\nProcess: $ps\n"
		ps | grep `basename $0` | grep -v grep
		echo -e "\nLeaving virtual filesystems unmounted (`pidof tazdev`)...\n"
	fi
}

# Get the last cooking base rootfs, extract and configure.
gen_new_chroot()
{
	echo -e "\nGenerating new chroot in : $ROOTFS"
	echo "================================================================================"
	mkdir -p $ROOTFS && cd $ROOTFS
	wget $DL_URL/boot/cooking/rootfs-base.gz
	echo -n "Extracting the rootfs..."
	lzma d rootfs-base.gz -so | cpio -id
	rm rootfs-base.gz
	echo -n "Creating resolv.conf..."
	cat /etc/resolv.conf > etc/resolv.conf
	status
	echo "================================================================================"
	echo -e "Ready to chroot. Use 'tazdev chroot [version|path]'"
	echo -e "Example: tazdev chroot $ROOTFS\n"
}

# Remove obsolate slitaz packages
purge_packages()
{
	arg=$1
	TMP_FILE=/tmp/tazdev.$$
	ls $BUILD_WOK | while read pkg; do
		[ -f $BUILD_WOK/$pkg/taz/*/receipt ] || continue
		EXTRAVERSION=""
		. $BUILD_WOK/$pkg/taz/*/receipt
		echo $PACKAGE-$VERSION$EXTRAVERSION.tazpkg
	done > $TMP_FILE
	ls $SLITAZ/chroot/home/slitaz/packages | while read pkg; do
		case "$pkg" in
		*.tazpkg)
			grep -q ^$pkg$ $TMP_FILE && continue
			echo Remove $pkg
			[ "$arg" == "purge" ] &&
			rm -f $SLITAZ/chroot/home/slitaz/packages/$pkg ;;
		esac
	done
	rm -f $TMP_FILE
}

# Remove obsolate source tarballs
purge_sources()
{
	arg=$1
	TMP_FILE=/tmp/tazdev.$$
	ls $BUILD_WOK | while read pkg; do
		[ -f $BUILD_WOK/$pkg/receipt ] || continue
		TARBALL=""
		. $BUILD_WOK/$pkg/receipt
		[ -n "$TARBALL" ] && echo $TARBALL
		grep SOURCES_REPOSITORY/ $BUILD_WOK/$pkg/receipt | sed \
		-e 's|.*SOURCES_REPOSITORY/\([^ ]*\)\( .*\)$|\1|' \
		-e 's|.*SOURCES_REPOSITORY/\([^ ]*\)$|\1|' | sort | uniq | \
		sed "s|['\"/]||g" | while read file ; do
			eval echo $file 2> /dev/null
		done
	done > $TMP_FILE
	ls $SLITAZ/chroot/home/slitaz/src | while read pkg; do
		grep -q ^$pkg$ $TMP_FILE && continue
		echo Remove $pkg
		[ "$arg" == "purge" ] &&
		rm -f $SLITAZ/chroot/home/slitaz/src/$pkg
	done
	rm -f $TMP_FILE
}

case "$1" in
	cmplog)
		# Log 'tazwok cmp' for the web interface (can be used via a cron job).
		check_root
		echo -e "Starting 'tazwok cmp' (can be long)...\n"
		tazwok cmp | grep ^[A-Z] | tee $CMP_LOG
		echo "Date: `date`" >> $CMP_LOG ;;
	projects-stats|-ps)
		echo -e "\nStatistics for: $PROJECTS\n"
		echo -n "Project" && echo -ne "\033[24G Size" && echo -ne "\033[38G Revision"
		echo -ne "\033[48G Version" && echo -e "\033[64G Files"
		echo "================================================================================"
		cd $PROJECTS
		for proj in *
		do
			rev=""
			echo -n "$proj"
			size=`du -sh $proj | awk '{ print $1 }'`
			echo -ne "\033[24G $size"
			if [ -d $proj/.hg ]; then
				cd $proj
				rev=`hg head --template '{rev}\n'`
				vers=`hg tags | head -n 2 | tail -n 1 | cut -d " " -f 1`
				echo -ne "\033[38G $rev"
				echo -ne "\033[48G $vers" && cd ..
			fi
			files=`find $proj -type f | wc -l`
			echo -e "\033[64G $files"
		done
		echo "================================================================================"
		echo "" ;;
	update-wok)
		# Update the Hg wok and copy it to the chroot env. Hg wok is
		# copied to the chroot wok to avoid messing with build result
		# file and so we can also modify receipt directly without affecting
		# the Hg wok.
		check_root
		get_version $@
		echo ""
		echo "Hg wok    : $HG_WOK"
		echo "Build wok : $BUILD_WOK"
		cd $HG_WOK
		hg pull && hg update
		echo -n "Copying Hg wok to the build wok... "
		cp -a $HG_WOK/* $BUILD_WOK
		cp -a $HG_WOK/.hg $BUILD_WOK
		status && echo "" ;;
	chroot)
		# Chroot into a build env. Default to cooking configured in
		# tazdev.conf
		check_root
		get_version $@
		mount_chroot
		echo -e "\nChrooting in $ROOTFS...\n"
		chroot $ROOTFS /bin/sh --login
		umount_chroot
		echo -e "Exiting $ROOTFS chroot environment...\n" ;;
	gen-chroot)
		check_root
		get_version $@
		# Dont break another env.
		if [ -d $ROOTFS/bin ]; then
			echo -e "\nA chroot environment already exists in : $ROOTFS\n"
			exit 1
		fi
		gen_new_chroot ;;
	clean-chroot)
		# Keep root/ and /home they may have a build wok, custom scripts, etc.
		check_root
		if [ -z "$2" ]; then
			echo -e "\nPlease specify the path to the chroot environment to clean.\n"
			exit 0
		else
			ROOTFS=$2
			if [ ! -d "$ROOTFS" ]; then
				echo -e "\nWarning : $ROOTFS doesn't exist!\n"
				exit 1
			fi
		fi
		if [ -d $ROOTFS/proc/1 ]; then
			echo -e "\nWarning : $ROOTFS/proc mounted!\n"
			exit 1
		fi
		cd $ROOTFS || exit 1
		echo -e "\nCleaning chroot in: $ROOTFS"
		echo "================================================================================"
		for i in bin dev etc init lib media mnt proc sbin sys tmp usr var
		do
			echo -n "Removing: $i (`du -sh $i | awk '{ print $1 }'`)... "
			rm -rf $i
			status
		done
		echo "================================================================================"
		echo "" ;;
	push|-p)
		check_mirror $@
		rsync -r -t -l -v -z --delete \
			$LOCAL_DIR -e ssh $USER@$MIRROR:$REMOTE_DIR ;;
	dry-push|-dp)
		check_mirror $@
		rsync -r -t -l -v -z --delete --dry-run \
			$LOCAL_DIR -e ssh $USER@$MIRROR:$REMOTE_DIR ;;
	pull)
		check_mirror $@
		rsync -r -t -l -v -z --delete \
			-e ssh $USER@$MIRROR:$REMOTE_DIR $LOCAL_DIR ;;
	dry-pull)
		check_mirror $@
		rsync -r -t -l -v -z --delete --dry-run \
			-e ssh $USER@$MIRROR:$REMOTE_DIR $LOCAL_DIR ;;
	purge|dry-purge)
		check_root
		get_version $@
		purge_packages $1
		purge_sources $1 ;;
	relpkg|-rp)
		[ -z "$MIRROR_SOURCES" ] && MIRROR_SOURCES="/var/www/slitaz/mirror/sources"
		if [ -z $2 ] || [ -z $3 ]; then
			echo -e "\nUsage: $0 relpkg package version\n"
			exit 0
		fi
		PACKAGE=$2
		VERSION=$3
		echo ""
		cd $PROJECTS/$PACKAGE
		# Sanity check
		if ! grep -q $VERSION$ .hgtags; then
			echo "Missing Hg tag for version: $VERSION"
			echo -e "You may want to: hg tag $VERSION && hg push\n"
			exit 0
		fi
		# Archive
		echo -n "Creating tarball and md5sum for: $PACKAGE-$VERSION... "
		hg archive -t tgz $PACKAGE-$VERSION.tar.gz
		md5sum $PACKAGE-$VERSION.tar.gz > $PACKAGE-$VERSION.md5
		echo "Done"
		# Upload
		echo -n "Do you wish to upload tarball to the mirror [N/y] ? "
		read upload
		if [ "$upload" = "y" ]; then
			echo "Uploading to: $MIRROR/sources/${PACKAGE#slitaz-}"
			scp $PACKAGE-$VERSION.tar.gz $PACKAGE-$VERSION.md5 \
				$USER@$MIRROR:$MIRROR_SOURCES/${PACKAGE#slitaz-}
		fi ;;
	reliso|-ri)
		# Generate all official images iso at once.
		version=$2
		mkdir -p $ISO
		for flavor in base core justx firefox
		do
			cd /home/slitaz/$version
			tazlito pack-flavor $flavor
			tazlito get-flavor $flavor
			tazlito gen-distro
			if [ "$flavor" == "core" ]; then
				cp distro/slitaz-$flavor.iso $ISO/slitaz-$version.iso
				cd $ISO && md5sum slitaz-$version.iso > slitaz-$version.md5
			else
				cp distro/slitaz-$flavor.iso $ISO/slitaz-$version-$flavor.iso
				cd $ISO && md5sum slitaz-$version-$flavor.iso slitaz-$version-$flavor.md5
			fi
		done ;;
	usage|*)
		usage ;;
esac

exit 0
