#!/bin/sh
#
# Copyright (c) 2008-2010 Juan Romero Pardines.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#-
: ${XBPS_CONFIG_FILE:=@@XBPS_INSTALL_ETCDIR@@/xbps-src.conf}

: ${progname:=$(basename $0)}
: ${fakeroot_cmd:=/usr/bin/fakeroot}
: ${fakeroot_cmd_args:=--}
: ${sudo_cmd:=sudo}
: ${chroot_cmd:=chroot}
: ${xbps_machine:=$(uname -m)}
: ${XBPS_UTILS_REQVER:=20100511}

trap '_MASTERDIR=${XBPS_MASTERDIR} sighandler_exit $?' 0 INT QUIT

sighandler_exit()
{
	# Always unmount in case we failed before!
	if [ -z "$in_chroot" ]; then
        	env MASTERDIR="${_MASTERDIR}" \
			@@XBPS_INSTALL_LIBEXECDIR@@/xbps-src-chroot-helper umount
	fi
	[ -n "$1" ] && exit $1
	exit $?
}

check_reqhost_utils()
{
	[ -n "$in_chroot" ] && return 0

	echo -n "=> Checking for required host utilities... "
	for f in awk bash sed gcc msgfmt patch makeinfo perl fakeroot \
		xbps-bin.static xbps-repo.static xbps-uhelper.static; do
		if ! command -v ${f} 2>&1 >/dev/null; then
			echo
			echo "${f} is missing in your system, can't continue! exiting..."
			exit 1
		fi
	done
	echo "done."
}

usage()
{
	cat << _EOF
$progname: [-Ch] [-c <file>] [-m <dir>] [-p <dir>] [-s <dir>] <target>

Targets:
 bootstrap        Build and install the bootstrap packages into <masterdir>.
 build            Build a package (fetch + extract + configure + build).
 build-pkg [all]  Build a binary package from <pkg>.
                  Package must be installed into destdir. If the <all>
                  keyword is used all packages currently installed in
		  <masterdir>/<destdir> will be used.
 checkvers        Checks installed package versions against srcpkgs
                  for new available versions.
 chroot           Enter to the chroot in <masterdir>.
 clean            Remove <pkg> build directory.
 configure        Configure a package (fetch + extract + configure).
 extract          Extract distribution file(s) into build directory.
                  Build directory is always available in
		  <masterdir>/pkg-builddir/<pkg>.
 fetch            Download distribution file(s).
 info             Show information for current pkg build template.
 install-destdir  build + install into destdir.
 install          install-destdir + stow.
 list             List installed packages in <masterdir>.
 listfiles        List installed files from <pkg>.
 make-repoidx     Build a package index for the local repository associated
                  with the master directory <masterdir> or <pkgdir>,
		  or updates it.
 remove           Remove package completely (destdir + masterdir).
 stow             Stow <pkg> files from <destdir> into <masterdir> and
                  register package in database.
 unstow           Remove <pkg> files from <masterdir> and unregister
                  package from database.

Options:
 -C     Do not remove build directory after successful installation.
 -c     Path to global configuration file:
        if not specified @@XBPS_INSTALL_ETCDIR@@/xbps-src.conf is used.
 -h	Usage output.
 -m     Master directory, overwritting the value set in the configuration
        file at @@XBPS_INSTALL_ETCDIR@@/xbps-src.conf.
 -p     Package directory, overwritting default path at
        <masterdir>/pkg-binpkgs.
 -s     Source distribution files directory, overwritting default path at
        <masterdir>/pkg-srcdistdir.

_EOF
}

basename_cwd()
{
	echo $(basename $(pwd))
}

check_path()
{
	eval local orig="$1"

	case "$orig" in
		/) ;;
		/*) orig="${orig%/}" ;;
		*) orig="$(pwd)/${orig%/}" ;;
	esac

	path_fixed="$orig"
}

run_file()
{
	local file="$1"

	check_path "$file"
	. $path_fixed
}

check_config_vars()
{
	local val cffound f cfpaths cf="xbps-src.conf"

	if [ -z "$XBPS_CONFIG_FILE" ]; then
		cfpaths="@@XBPS_INSTALL_PREFIX@@/etc/${cf} ./etc/${cf}"
		for f in $cfpaths; do
			if [ -f ${f} ]; then
				XBPS_CONFIG_FILE=${f}
				cffound=yes
				break
			fi
		done
		[ -z "$cffound" ] && msg_error "cannot find a config file"
	fi

	run_file ${XBPS_CONFIG_FILE}
	export XBPS_CONFIG_FILE=$path_fixed

	if [ ! -f "$XBPS_CONFIG_FILE" ]; then
		msg_error "cannot find configuration file: $XBPS_CONFIG_FILE"
	fi

	for f in XBPS_DISTRIBUTIONDIR XBPS_MASTERDIR; do
		eval val="\$${f}"
		if [ -z "$val" ]; then
			msg_error "'${f}' not set in configuration file!"
		fi
	done
	if [ ! -d "$XBPS_MASTERDIR" ]; then
		mkdir -p "$val"
		if [ $? -ne 0 ]; then
			msg_error "couldn't create 'XBPS_MASTERDIR' directory"
		fi
	fi
	[ -z "${_MASTERDIR_FLAG}" ] && export _MASTERDIR="$XBPS_MASTERDIR"
}

#
# main()
#
while getopts "Cc:hm:p:s:" opt; do
	case $opt in
		C) export dontrm_builddir=yes;;
		c) XBPS_CONFIG_FILE="$OPTARG";;
		h) usage && exit 0;;
		m)
			_MASTERDIR_FLAG=1
			_MASTERDIR="$OPTARG"
			if [ ! -d ${_MASTERDIR} ]; then
				mkdir -p ${_MASTERDIR}
			fi
			;;
		p)
			_PACKAGEDIR="$OPTARG"
			if [ ! -d ${_PACKAGEDIR} ]; then
				mkdir -p ${_PACKAGEDIR}/${xbps_machine}
				mkdir -p ${_PACKAGEDIR}/noarch
			fi
			;;
		s) export XBPS_SRCDISTDIR="$OPTARG";;
		--) shift; break;;
	esac
done
shift $(($OPTIND - 1))

[ $# -eq 0 -o $# -gt 2 ] && usage && exit 1

target="$1"
if [ -z "$target" ]; then
	echo "=> ERROR: missing target."
	usage && exit 1
fi

#
# Check for required utilities in host system.
#
check_reqhost_utils

if [ -n "$in_chroot" ]; then
	XBPS_CONFIG_FILE="/usr/local/etc/xbps-src.conf"
fi

#
# Check configuration vars before anyting else, and set defaults vars.
#
check_config_vars
if [ -n "${_MASTERDIR}" ]; then
	export XBPS_MASTERDIR=${_MASTERDIR}
fi
. @@XBPS_INSTALL_SHAREDIR@@/shutils/init_funcs.sh
set_defvars

. $XBPS_SHUTILSDIR/common_funcs.sh

#
# Fix up some vars when XBPS_USE_CAPABILITIES is set.
#
if [ -n "$XBPS_USE_CAPABILITIES" ]; then
	chroot_cmd="@@XBPS_INSTALL_LIBEXECDIR@@/xbps-src-capchroot"
	unset sudo_cmd
fi

if [ "$(id -u)" -eq 0 ]; then
	# disable sudo and fakeroot if uid==0
	chroot_cmd="chroot"
	unset sudo_cmd
	if [ -n "$in_chroot" ]; then
		unset fakeroot_cmd
		unset fakeroot_cmd_args
	fi
fi

[ -z "$dontrm_builddir" ] && dontrm_builddir=no

#
# Sanitize PATH.
#
if [ -z "$in_chroot" ]; then
	# In non chroot case always prefer host tools.
	MYPATH="$XBPS_MASTERDIR/bin:$XBPS_MASTERDIR/usr/bin:$PATH"
	MYPATH="$XBPS_MASTERDIR/usr/local/bin:$MYPATH"
	MYPATH="$XBPS_MASTERDIR/usr/local/sbin:$MYPATH"
else
	# In chroot always prefer tools from bootstrap.
	MYPATH="/tools/bin:/usr/local/sbin:/usr/local/bin"
	MYPATH="/bin:/sbin:/usr/bin:/usr/sbin:$MYPATH"
fi
export PATH="$MYPATH"

#
# Main switch.
#
case "$target" in
bootstrap)
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	. $XBPS_SHUTILSDIR/pkgtarget_funcs.sh
	[ ! -d $XBPS_SRCPKGDIR/xbps-base-chroot ] && \
		msg_error "Cannot find $XBPS_SRCPKGDIR/xbps-base-chroot directory!"
	cd $XBPS_SRCPKGDIR/xbps-base-chroot && _ORIGINPKG="$(basename_cwd)"
	setup_tmpl ${_ORIGINPKG} && install_pkg $pkgname
	;;
build|configure)
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	[ ! -r ./template ] && msg_error "missing build template in $(pwd)."
	. ./template

	if [ -z "$base_chroot" -a -z "$in_chroot" ]; then
		. $XBPS_SHUTILSDIR/chroot.sh
		xbps_chroot_handler $target $(basename_cwd)
	else
		_ORIGINPKG="$(basename_cwd)"
		setup_tmpl ${_ORIGINPKG}
		# If pkg has dependencies, install them first.
		. $XBPS_SHUTILSDIR/pkgtarget_funcs.sh
		. $XBPS_SHUTILSDIR/builddep_funcs.sh
		install_dependencies_pkg "$pkgname-$version"
		if [ $? -ne 0 ]; then
			msg_red "cannot install required deps for $pkgname."
			exit 1
		fi
		# All deps were installed, continue with the origin pkg...
		setup_tmpl ${_ORIGINPKG}
		. $XBPS_SHUTILSDIR/fetch_funcs.sh
		fetch_distfiles
		if [ ! -f "$XBPS_EXTRACT_DONE" ]; then
			. $XBPS_SHUTILSDIR/extract_funcs.sh
			extract_distfiles
		fi
		if [ "$target" = "configure" ]; then
			. $XBPS_SHUTILSDIR/configure_funcs.sh
			configure_src_phase
		else
			if [ ! -f "$XBPS_CONFIGURE_DONE" ]; then
				. $XBPS_SHUTILSDIR/configure_funcs.sh
				configure_src_phase
			fi
			. $XBPS_SHUTILSDIR/build_funcs.sh
			build_src_phase
		fi
	fi
	;;
build-pkg)
	. $XBPS_SHUTILSDIR/make-binpkg.sh
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	if [ -n "${_PACKAGEDIR}" ]; then
		export XBPS_PACKAGESDIR=${_PACKAGEDIR}
	fi
	if [ "$2" = "all" ]; then
		for f in $($XBPS_BIN_CMD list|awk '{print $1}'); do
			pkg=$(${XBPS_PKGDB_CMD} getpkgname $f)
			setup_tmpl $pkg
			if [ "${pkg}" = "${sourcepkg}" ]; then
				xbps_make_binpkg
			fi
		done
	else
		[ ! -r ./template ] && msg_error "missing build template in $(pwd)."
		setup_tmpl $(basename_cwd)
		xbps_make_binpkg
	fi
	;;
checkvers)
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	. $XBPS_SHUTILSDIR/check_installed_packages.sh
	check_installed_packages
	;;
chroot)
	. $XBPS_SHUTILSDIR/chroot.sh
	xbps_chroot_handler chroot dummy
	;;
clean)
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	[ ! -r ./template ] && msg_error "missing build template in $(pwd)."
	setup_tmpl $(basename_cwd)
	remove_tmpl_wrksrc $wrksrc
	;;
extract|fetch|info)
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	[ ! -r ./template ] && msg_error "missing build template in $(pwd)."
	setup_tmpl $(basename_cwd)
	if [ "$target" = "info" ]; then
		. $XBPS_SHUTILSDIR/tmpl_funcs.sh
		info_tmpl
		exit $?
	fi
	if [ "$target" = "fetch" ]; then
		. $XBPS_SHUTILSDIR/fetch_funcs.sh
		fetch_distfiles $update_checksum
		exit $?
	fi
	. $XBPS_SHUTILSDIR/extract_funcs.sh
	extract_distfiles
	;;
install|install-destdir)
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	[ ! -r ./template ] && msg_error "missing build template in $(pwd)."
	. ./template

	install_destdir_target=no
	[ "$target" = "install-destdir" ] && install_destdir_target=yes

	_ORIGINPKG="$(basename_cwd)"
	if [ -z "$in_chroot" -a -z "$base_chroot" ]; then
		. $XBPS_SHUTILSDIR/chroot.sh
		xbps_chroot_handler $target ${_ORIGINPKG} $dontrm_builddir
	else
		. $XBPS_SHUTILSDIR/pkgtarget_funcs.sh
		setup_tmpl ${_ORIGINPKG}
		install_pkg $pkgname
	fi
	;;
list|listfiles)
	if [ "$target" = "list" ]; then
		$XBPS_BIN_CMD list
		exit $?
	fi
	. $XBPS_SHUTILSDIR/pkgtarget_funcs.sh
	list_pkg_files $2
	;;
make-repoidx)
	if [ -n "${_PACKAGEDIR}" ]; then
		export XBPS_PACKAGESDIR=${_PACKAGEDIR}
	fi
	echo "=> Updating package index for local repository at"
	echo "   $XBPS_PACKAGESDIR..."
	${XBPS_REPO_CMD} genindex ${XBPS_PACKAGESDIR} 2>/dev/null
	[ $? -eq 0 ] && echo "=> done."
	;;
remove)
	. $XBPS_SHUTILSDIR/pkgtarget_funcs.sh
	[ ! -r ./template ] && msg_error "missing build template in $(pwd)."
	setup_tmpl $(basename_cwd)
	remove_pkg
	;;
stow)
	stow_flag=yes
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	[ ! -r ./template ] && msg_error "missing build template in $(pwd)."
	setup_tmpl $(basename_cwd)
	. $XBPS_SHUTILSDIR/stow_funcs.sh
	stow_pkg_handler stow
	;;
unstow)
	. $XBPS_SHUTILSDIR/tmpl_funcs.sh
	[ ! -r ./template ] && msg_error "missing build template in $(pwd)."
	setup_tmpl $(basename_cwd)
	. $XBPS_SHUTILSDIR/stow_funcs.sh
	stow_pkg_handler unstow
	;;
*)
	echo "=> ERROR: invalid target: $target."
	usage && exit 1
esac

# Agur
exit $?