#!/bin/sh

usage()
{
	cat << EOF

USAGE:
  --target  TARGEET            target triplet
  --subset  SUBSET             the name of a file containing a list of packages
                               to be added to the distribution; otherwise,
                               the name of a project-provided subset; multiple
                               subsets are allowed and may overlap in one or
                               more packages

  --minroot MINIPIX_ROOT       location of the top-level minipix directory
  --objroot OBJECT_ROOT        location of the top-level object directory

  --usrpkgs USER_PKGS          a folder containing user-provided distribution tarballs
  --usrdata USER_DATA          a folder containing user-provided installation files

  --tmproot TEMPORARY_ROOT     where temporary files should be created
  --pkgroot PACKAGE_ROOT       where package tarballs should be created
  --sysroot SYSTEM_ROOT        where the live distribution should be created

  --zipfile ZIPFILE_NAME       name of the zipfile to be created (optional)

  --symbols                    do not strip PE binaries (distro)
  --flysyms                    do not strip PE binaries (live environment)

  --defroot                    default location to which the distribution should
                                       be installed (substitutes @sysroot@)
  --product                    name of the distribution to be installed
                                       (substitutes @product@)

EOF
	exit 1
}

error_msg()
{
	echo $@ >&2
	exit 2
}

init_vars()
{
	# project
	mb_project_dir=$(cd `dirname $0` ; pwd)
	mb_pwd=`pwd`

	# subsets
	mb_subset=
	mb_subsets=
	mb_pkglist=

	# target
	mb_target=$TARGET

	# midipix_build directories
	mb_minroot=$MINIPIX_ROOT
	mb_objroot=$OBJECT_ROOT

	# user directories
	mb_usrpkgs=$USER_PKGS
	mb_usrdata=$USER_DATA

	# mpackage directories
	mb_tmproot=$TEMPORARY_ROOT
	mb_pkgroot=$PACKAGE_ROOT
	mb_sysroot=$SYSTEM_ROOT

	# symbols
	mb_symbols='no'
	mb_flysyms='no'

	# setup
	mb_defroot=@sysroot@
	mb_product=@product@

	# and voila
	mb_zipfile=$ZIPFILE_NAME
}

validate_args()
{
	[ -z "$mb_target" ]  && error_msg "!! target not set, quitting..."

	[ -z "$mb_minroot" ] && error_msg "!! minroot not set, quitting..."
	[ -z "$mb_objroot" ] && error_msg "!! objroot not set, quitting..."

	[ -z "$mb_tmproot" ] && error_msg "!! tmproot not set, quitting..."
	[ -z "$mb_pkgroot" ] && error_msg "!! pkgroot not set, quitting..."
	[ -z "$mb_sysroot" ] && error_msg "!! sysroot not set, quitting..."


	if ! [ -d "$mb_minroot" ]; then
		error_msg "!! $mb_minroot: minroot directory not found, quitting..."
	fi

	if ! [ -d "$mb_objroot" ]; then
		error_msg "!! $mb_objroot: objroot directory not found, quitting..."
	fi


	if ! [ -z "$mb_usrpkgs" ] && ! [ -d "$mb_usrpkgs" ]; then
		error_msg "!! $mb_usrpkgs: usrpkgs directory does not exist, quitting..."
	fi

	if ! [ -z "$mb_usrdata" ] && ! [ -d "$mb_usrdata" ]; then
		error_msg "!! $mb_usrdata: usrdata directory does not exist, quitting..."
	fi

	if ! [ -z "$mb_zipfile" ] && ! [ -d `dirname "$mb_zipfile"` ]; then
		error_msg "!! $mb_zipfile: zipfile directory does not exist, quitting..."
	fi


	if [ -d "$mb_tmproot" ]; then
		error_msg "!! $mb_tmproot: tmproot directory already exists, quitting..."
	fi

	if [ -d "$mb_pkgroot" ]; then
		error_msg "!! $mb_pkgroot: pkgroot directory already exists, quitting..."
	fi

	if [ -d "$mb_sysroot" ]; then
		error_msg "!! $mb_sysroot: sysroot directory already exists, quitting..."
	fi
}

init_dirs()
{
	mkdir "$mb_tmproot" || exit 2
	mkdir "$mb_pkgroot" || exit 2
	mkdir "$mb_sysroot" || exit 2

	mb_minroot=$(cd "$mb_minroot" ; pwd)
	mb_objroot=$(cd "$mb_objroot" ; pwd)

	mb_tmproot=$(cd "$mb_tmproot" ; pwd)
	mb_pkgroot=$(cd "$mb_pkgroot" ; pwd)
	mb_sysroot=$(cd "$mb_sysroot" ; pwd)

	if ! [ -z "$mb_usrpkgs" ]; then
		mb_usrpkgs=$(cd "$mb_usrpkgs" ; pwd)
	fi

	if ! [ -z "$mb_usrpkgs" ]; then
		mb_usrdata=$(cd "$mb_usrdata" ; pwd)
	fi

	if ! [ -z "$mb_zipfile" ]; then
		mb_zipdir=$(cd `dirname "$mb_zipfile"` ; pwd)
		mb_zipbase=`basename "$mb_zipfile"`
		mb_zipfile="$mb_zipdir/$mb_zipbase"
	fi
}

init_pkglist()
{
	if [ -z "$mb_subsets" ]; then
		mb_pkglist=''
	else
		mb_srclist=''

		for subset in $mb_subsets; do
			if [ -f $subset ]; then
				mb_srclist="$mb_srclist $subset"
			elif [ -f "$mb_project_dir/subset/$subset" ]; then
				mb_srclist="$mb_srclist $mb_project_dir/subset/$subset"
			else
				error_msg "!! $subset: subset not found, quitting..."
			fi
		done

		mb_pkglist=`cat $mb_srclist | grep -v '#' | sort --unique`

		echo "$mb_pkglist"
	fi
}

strip_symbols()
{
	( perk -y $f 2>/dev/null | grep -v '\-obj\-' >/dev/null ) \
		&& ( strip $1 || exit 2 )
}

gen_setup()
{
	pkgdir="$mb_tmproot/once"
	objdir="$mb_project_dir/once"

	cp  -av "$objdir" "$pkgdir"     || exit 2
	cd "$pkgdir"                    || exit 2

	for f in $(find -type f); do
		sed -e 's#@sysroot@#'"$mb_defroot"'#g' \
		    -e 's#@product@#'"$mb_product"'#g' \
		    -e 's#@SYSROOT@#'"@sysroot@"'#g'   \
		   $f  >  $f.tmp        || exit 2

		cat $f.tmp > $f         || exit 2
		rm $f.tmp               || exit 2
	done
}

gen_tarballs()
{
	for pkg in $mb_pkglist; do
		pkgdir="$mb_tmproot/$pkg"
		objdir="$mb_objroot/$pkg-native-$mb_target/destdir"

		cp  -av "$objdir" "$pkgdir"           || exit 2
		cd "$pkgdir"                          || exit 2

		for f in $(find -type f); do
			if [ $mb_symbols = 'no' ]; then
				strip_symbols $f
			fi
		done

		tar -cvzf "$mb_pkgroot/$pkg.tar.gz" * || exit 2
	done

	# common, distro
	for pkg in common distro; do
		cd "$mb_project_dir/$pkg"
		tar -cvzf "$mb_pkgroot/$pkg.tar.gz" * || exit 2
	done
}

gen_sysroot()
{
	# layout
	mkdir "$mb_sysroot/tarballs"    || exit 2
	mkdir "$mb_sysroot/updates"     || exit 2

	# minipix
	cd "$mb_minroot"                || exit 2
	cp -av * "$mb_sysroot"          || exit 2
	cd "$mb_sysroot"                || exit 2

	for f in $(find -type f); do
		if [ $mb_flysyms = 'no' ]; then
			strip_symbols $f
		fi
	done

	# common
	cd "$mb_project_dir/common"     || exit 2
	cp -av * "$mb_sysroot"          || exit 2

	# once
	cd "$mb_tmproot/once"           || exit 2
	cp -av * "$mb_sysroot"          || exit 2

	# tarballs
	cd "$mb_pkgroot"                || exit 2
	cp -av * "$mb_sysroot/tarballs" || exit 2

	# user packages
	if ! [ -z "$mb_usrpkgs" ]; then
		cd "$mb_usrpkgs"                || exit 2
		cp -av * "$mb_sysroot/tarballs" || exit 2
	fi

	# user installation scripts
	if ! [ -z "$mb_usrdata" ]; then
		cd "$mb_usrdata"                || exit 2
		cp -av * "$mb_sysroot"          || exit 2
	fi
}

gen_zipfile()
{
	if [ -z "$mb_zipfile" ]; then
		return 0
	fi

	cd "$mb_sysroot"         || exit 2
	zip -rv9 "$mb_zipfile" * || exit 2
}

# one: vars
init_vars

# two: args
for arg ; do
	case "$arg" in
		--help)	usage
			;;
		--target=*)
			mb_target=${arg#*=}
			;;
		--minroot=*)
			mb_minroot=${arg#*=}
			;;
		--objroot=*)
			mb_objroot=${arg#*=}
			;;
		--usrpkgs=*)
			mb_usrpkgs=${arg#*=}
			;;
		--usrdata=*)
			mb_usrdata=${arg#*=}
			;;
		--tmproot=*)
			mb_tmproot=${arg#*=}
			;;
		--pkgroot=*)
			mb_pkgroot=${arg#*=}
			;;
		--sysroot=*)
			mb_sysroot=${arg#*=}
			;;
		--zipfile=*)
			mb_zipfile=${arg#*=}
			;;
		--defroot=*)
			mb_defroot=${arg#*=}
			;;
		--product=*)
			mb_product=${arg#*=}
			;;
		--symbols)
			mb_symbols='yes'
			;;
		--flysyms)
			mb_flysyms='yes'
			;;
		--subset=*)
			mb_subset=${arg#*=}
			mb_subsets="$mb_subsets $mb_subset"
			;;
		*)
			error_msg ${arg#}: "unsupported script argument."
			exit 2
			;;
	esac
done

# three: sanity
validate_args

# four:  dirs, package list
init_dirs
init_pkglist

# five:  tarballs, sysroot, setup
gen_setup
gen_tarballs
gen_sysroot

# six:   zipfile
gen_zipfile

# all done
exit 0
