#!/bin/bash

initialize-variables(){
    ## set boolian variables
    with_profile=0
    with_setup_vbootstrap=0
    with_dist_upgrade=0
    with_unionfs=0
    with_sign=0
    with_no_install=0
    with_login=0
    with_debug=0
    with_actions=0
    with_ix86_on_x86_64=0
    with_category_main=0
    with_category_plus=0
    with_category_nonfree=0
    with_category_test=0
    with_category_proposed_updates=0
    with_category_security=0

    return 0
}

check-parameter(){
    [ -z "$*" ] && Usage && return 1

    while [ ! -z "$*" ]; do
	case $1 in
	    --help|help)
		setup-vbuilder ||:
		Usage
		return 1
		;;
	    --profile)
		shift
		with_profile=1
		PROFILE=$1
		check-next-parameter $1 || return 1
		;;
	    --version|--arch|--category|--fetch-url|--target|--rpmbuild-define|--rpmbuild-with|--rpmbuild-without|--bootstrap-dir|--unionfs-dir|--cache-dir|--built-rpms-dir)
		[ $with_actions -eq 1 ] && \
		    echo $"E: You can give no more options after actions" && \
		    return 1
		shift
		check-next-parameter $1 || return 1
		;;
	    --dist-upgrade|--unionfs|--with-compat32|--sign|--no-install|--login|--debug)
		[ $with_actions -eq 1 ] && \
		    echo $"E: You can give no more options after actions" && \
		    return 1
		;;
	    --build-rpm|build-rpm|--install-rpm|install-rpm|--remove-rpm|remove-rpm)
		with_actions=1
		shift
		check-next-parameter $1 || return 1
		;;
	    --build|build|--clean|clean)
		with_actions=1
		;;
	    *)
		echo $"E: Missing some parameters after $1"
		return 1
		;;
	esac
	shift
    done

    [ $with_actions -eq 0 ] && \
	echo $"E: You must give at least one action" && return 1

    return 0
}

check-next-parameter(){
    [ -z "$1" ] && echo $"E: Missing some parameters after $1" && return 1

    [ $(echo $1 | grep '^-') ] && \
	echo $"E: Missing some parameters after $1" && return 1

    return 0
}

## NOTE: setup-vbuilder() loads
##  - system wide configurations (from /etc/vbootstrap/vbuilder.conf)
##  - given profile (from /etc/vbootstrap/profile.d/*.conf)
##  - given command-line parameters 
## where given command-line parameters override the settings given profile, 
## and the settings given profile override system wide settings. 
## If you use a profile of vbuilder, you may not override the settings 
## given profile. 
setup-vbuilder(){
    ## check $SUDO_USER and $USERHELPER_UID
    RPM_SIGN_USER=$SUDO_USER
    if [ -z "${RPM_SIGN_USER}" ]; then
	[ -z "${USERHELPER_UID}" ] && \
	    echo $"W: \$SUDO_USER and \$USERHELPER_UID are empty" && \
	    return 1
	    
	RPM_SIGN_USER=$(getent passwd $USERHELPER_UID | cut -d":" -f1)
    fi
    ## get $RPM_SIGN_USER's home directory
    HOME=$(getent passwd $RPM_SIGN_USER |  cut -d":" -f6)

    ## load default settings
    VBUILDER_CONF=/etc/vbootstrap/vbuilder.conf
    if [ -r $VBUILDER_CONF ]; then
	. $VBUILDER_CONF
	[ $? -eq 1 ] && return 1
    fi
    [ -z "${CATEGORIES}" ] && \
	CATEGORIES=@@VBUILDER_CATEGORIES@@
    [ -z "${VBOOTSTRAP_FETCH_URL}" ] && \
	VBOOTSTRAP_FETCH_URL=@@VBUILDER_VBOOTSTRAP_FETCH_URL@@
    [ -z "${VBOOTSTRAP_DIR}" ] && \
	VBOOTSTRAP_DIR=@@VBUILDER_VBOOTSTRAP_DIR@@
    [ -z "${UNIONFS_DIR}" ] && \
	UNIONFS_DIR=@@VBUILDER_UNIONFS_DIR@@
    [ -z "${CACHE_DIR}" ] && \
	CACHE_DIR=@@VBUILDER_CACHE_DIR@@
    [ -z "${BUILT_RPMS_DIR}" ] && \
	BUILT_RPMS_DIR=@@VBUILDER_BUILT_RPMS_DIR@@

    ## set default version for vbootstrap
    VERSION=@@VBUILDER_DEFAULT_VERSION@@

    ## load profile
    if [ ${with_profile} -eq 1 ]; then
	[ ! -r /etc/vbootstrap/profile.d/${PROFILE}.conf ] && \
	    echo $"E: No such profile found: ${PROFILE}" && return 1

	. /etc/vbootstrap/profile.d/${PROFILE}.conf
	[ $? -eq 1 ] && return 1
    fi

    ## set current stable relase version
    STABLE_VERSION=@@VBUILDER_STABLE_VERSION@@

    ## set default chroot archtecture
    UARCH=$(uname -i)
    case "${UARCH}" in
	arm*)
	    UARCH="arm"
	    ;;
    esac

    return 0
}

setup-vbootstrap(){
    if [ ${with_setup_vbootstrap} -eq 0 ]; then
	with_setup_vbootstrap=1

	## check debug mode
	[ ${with_debug} -eq 1 ] && \
	    cat $VBUILDER_CONF && \
	    set && set -x

	## check some directories
	## Note: create $BUILT_RPMS_DIR in RPM_Build()
	[ -d $VBOOTSTRAP_DIR ] || mkdir -p $VBOOTSTRAP_DIR
	[ -d $CACHE_DIR ] || mkdir -p $CACHE_DIR

	## check chroot version
	case ${VERSION} in
	    4.2|5.2|6|VineSeed)
		;;
	    6.?)
	    	VERSION="6"
		;;
	    *)
		echo $"E: ${VERSION} is NOT supported"
		return 1
		;;
	esac

	case "${VARCH}" in
	    arm*)
		VARCH="arm"
		;;
	esac

	## check a chroot archtecture
	if [ -z ${VARCH} ]; then
	    VARCH=${UARCH}
	else
	    case "${VARCH}" in
		i386|x86_64)
		    [ "${UARCH}" = "ppc" -o "${UARCH}" = "arm" ] && \
			echo $"E: arch ${VARCH} is NOT supported on ${UARCH}" && return 1
		    ;;
		ppc)
		    [ "${UARCH}" = "i386" -o "${UARCH}" = "x86_64" -o "${UARCH}" = "arm" ] && \
			echo $"E: arch ${VARCH} is NOT supported on ${UARCH}" && return 1
		    ;;
		arm)
		    [ "${UARCH}" = "i386" -o "${UARCH}" = "x86_64" -o "${UARCH}" = "ppc" ] && \
			echo $"E: arch ${VARCH} is NOT supported on ${UARCH}" && return 1
		    ;;
	    esac
	fi

        ##!! 4.2 is NO support on VARCH=x86_64 or VARCH=arch
	if [ "${VERSION}" = "4.2" ]; then
	    if [ "${VARCH}" = "x86_64" -o "${VARCH}" = "arm" ]; then
		echo $"E: ${VERSION}_${VARCH} is NOT supported"
		return 1
	    fi
	fi

	## set base profile <version>_<arch>
	BASE_PROFILE=${VERSION}_${VARCH}

        ## check support ${BASE_PROFILE}
	if [ -z "$(/usr/sbin/vbootstrap | sed -e s/^Usage:.*// -e s/^E:.*// | grep -m 1 ${BASE_PROFILE})" ]; then
	    echo $"E: ${BASE_PROFILE} is NOT supported"
	    return 1
	fi

	## check ${VERSION} equals VineSeed*, when with_dist_upgrade=1
	if [ $with_dist_upgrade -eq 1 ]; then
	    if [ "${VERSION}" != "VineSeed" ]; then 
		echo $"E: version ${VERSION} does not support --dist-upgrade option"
		return 1
	    fi
	fi

	## support i386 chroot on x86_64 below: 
	[ "${UARCH}" = "x86_64" -a "${VARCH}" = "i386" ] && \
	    with_ix86_on_x86_64=1

	## check apt categories
	## "main" category is unconditionally permited
	with_category_main=1
	for cat in $(echo ${CATEGORIES} | sed -e "s/,/ /"g); do
	    case $cat in
		main)
		    with_category_main=1
		    ;;
		plus)
		    with_category_plus=1
		    ;;
		nonfree)
		    with_category_nonfree=1
		    ;;
		test)
                    ## "test" category only exists in VineSeed
		    [ "${VERSION}" = "VineSeed" ] || \
			echo $"E: No such category exists: $cat" && return 1
		    with_category_test=1
		    ;;
		proposed-updates)
                    ##!! "proposed-updates" category does not exist in 4.2
		    [ "${VERSION}" = "4.2" ] && \
			echo $"E: No such category exists: $cat" && return 1

		    with_category_proposed_updates=1
		    ;;
		security)
                    ## "security" category does not exist in VineSeed
		    [ "${VERSION}" = "VineSeed" ] && \
			echo $"E: No such category exists: $cat" && return 1
		    with_category_security=1
		    ;;
		*)
		    echo $"E: No such category exists: $cat" && return 1
		    ;;
	    esac
	done

	## check build target option ${TARGET}
	if [ ! -z "${TARGET}" ]; then
	    RPM_TARGET_LIST="$(cat /usr/lib/rpm/rpmrc | grep arch_canon: | sed -e "s/arch_canon:[[:blank:]]*\(.*\):.*/\1/")"
	    RPM_TARGET_LIST="${RPM_TARGET_LIST} noarch"
	    if [ -z "$(echo ${RPM_TARGET_LIST} | grep ${TARGET})" ]; then
		echo $"E: rpm build target ${TARGET} is NOT supported"
		return 1
	    fi
	fi

	## set ${RPM_PKG_ARCH_LIST}
	RPM_PKG_ARCH_LIST=" \
            RPMS/i386 RPMS/i486 RPMS/i586 RPMS/i686 RPMS/x86_64 RPMS/ppc \
            RPMS/noarch \
            RPMS/armv3l RPMS/armv4l RPMS/armv4tl \
            RPMS/armv5tejl RPMS/armv5tel RPMS/armv6l RPMS/armv7l \
            SRPMS"
	[ -z "${TARGET}" ] || \
	    RPM_PKG_ARCH_LIST="RPMS/${TARGET} ${RPM_PKG_ARCH_LIST}"

    fi

    ## set global variables
    BUILD_USER=vbuilder
    BUILD_DIR=/home/${BUILD_USER}/rpm
    if [ ${with_profile} -eq 1 ]; then
	BUILD_ROOT=${VBOOTSTRAP_DIR}/${PROFILE}
	UNIONFS_ROOT=${UNIONFS_DIR}/${PROFILE}
    else
	BUILD_ROOT=${VBOOTSTRAP_DIR}/${BASE_PROFILE}
	UNIONFS_ROOT=${UNIONFS_DIR}/${BASE_PROFILE}
    fi
    ARCHIVES_DIR=${BUILD_ROOT}/var/cache/apt/archives
    EXTERNAL_ARCHIVES_DIR=${CACHE_DIR}/${BASE_PROFILE}/apt/archives

    __chroot_sh="/usr/sbin/chroot ${BUILD_ROOT} /bin/sh -c -l"

    mkdir -p $VBOOTSTRAP_DIR

    return 0
}

setup-vbootstrap-rpm(){
    setup-vbootstrap || return 1

    ## check ${BUILD_ROOT}
    [ -d ${BUILD_ROOT} ] || Build
    ## setarch ix86 if ix86 chroot on x86_64 host
    [ $with_ix86_on_x86_64 -eq 1 ] && \
	__chroot_sh="/usr/sbin/chroot ${BUILD_ROOT} setarch ${VARCH} /bin/sh -c -l"

    DIST_RELEASE=$(cat ${BUILD_ROOT}/etc/vine-release | cut -f3 -d" " | cut -f1 -d.)

    if [ -f $RPM_PKG ]; then
	BASE_RPM_PKG=$(basename $RPM_PKG)
	cp -f $RPM_PKG $BUILD_ROOT${BUILD_DIR}
    else
	BASE_RPM_PKG=$RPM_PKG	
    fi

    return 0
}

## recover apt-get data on host/chroot
apt-get-update(){
    case $1 in
	--host)
	    echo -n $"apt-get update on host ... "
	    apt-get -qq update > /dev/null 2>&1
	    echo $"done."
	    ;;
	--chroot)
	    echo -n $"apt-get update on chroot ... "
	    $__chroot_sh 'apt-get -qq update' > /dev/null 2>&1
	    echo $"done."
	    ;;
	*)
	    echo apt-get-update: unknown option $1
	    exit 1
	    ;;
    esac
}

## mount-chroot {|--umount} [file system|name]
## support file systems: /home /tmp /sys /proc /dev/shm /dev/pts /dev
## support names: vfs archives_dir
## NOTE: /tmp needs for applications which use X
##       vfs is virtual file systems
##       archives_dir uses to mount ${EXTERNAL_ARCHIVES_DIR} to ${ARCHIVES_DIR}
##       unionfs_dir covers ${BUILD_ROOT} with unionfs
mount-chroot(){
    if [ "$1" = "--umount" ]; then
	mount-chroot-umount $2 || return 1
    else
	mount-chroot-mount $1 || return 1
    fi
    return 0
}

## mount-chroot-umount [file system|name]
mount-chroot-umount(){
    local fs=$1
    case $fs in
	/home|/tmp|/sys|/proc|/dev/shm|/dev/pts|/dev)
	    [ -d ${BUILD_ROOT}${fs} ] || return 1
	    [ -z "$(mount | grep ${BUILD_ROOT}${fs})" ] || \
    		umount ${BUILD_ROOT}${fs}
	    if [ ! -z "$(mount | grep ${BUILD_ROOT}${fs})" ]; then
		echo $"Retry lazy unmount ${BUILD_ROOT}${fs} ... "
		umount -l ${BUILD_ROOT}${fs}
		echo $"done."
	    fi
	    ;;
	vfs)
	    for dir in /sys /proc /dev/shm /dev/pts /dev; do
	    	mount-chroot-umount ${dir} || return 1
	    done
	    ;;
	archives_dir)
	    [ -d ${ARCHIVES_DIR} ] || return 1
	    [ -z "$(mount | grep ${ARCHIVES_DIR})" ] || \
    		umount ${ARCHIVES_DIR}
	    ;;
	unionfs_dir)
	    [ -d ${BUILD_ROOT} ] || return 1
	    [ -z "$(mount | grep ${BUILD_ROOT} | egrep '(unionfs|aufs)')" ] || \
		umount ${BUILD_ROOT}
	    if [ ! -z "$(mount | grep ${BUILD_ROOT} | egrep '(unionfs|aufs)')" ]; then
		echo $"Retry lazy unmount ${BUILD_ROOT} ... "
		umount -l ${BUILD_ROOT}
		echo $"done."
	    fi
	    ;;
	*)
	    echo mount-chroot-umount: unknown file system $fs
	    exit 1
	    ;;
    esac
    return 0
}

## mount-chroot-mount [file system|name]
mount-chroot-mount(){
    local fs=$1

    case $fs in
	/home)
	    [ -d ${BUILD_ROOT}${fs} ] || mkdir -p ${BUILD_ROOT}${fs}
	    [ -z "$(mount | grep ${BUILD_ROOT}${fs})" ] && \
		mount -o _netdev,rbind ${fs} ${BUILD_ROOT}${fs}
	    ;;
	/tmp|/dev)
	    [ -d ${BUILD_ROOT}${fs} ] || mkdir -p ${BUILD_ROOT}${fs}
	    [ -z "$(mount | grep ${BUILD_ROOT}${fs})" ] && \
		mount --bind -o _netdev ${fs} ${BUILD_ROOT}${fs}
	    ;;
	/sys)
	    [ -d ${BUILD_ROOT}${fs} ] || mkdir -p ${BUILD_ROOT}${fs}
	    [ -z "$(mount | grep ${BUILD_ROOT}${fs})" ] && \
		mount -o _netdev -t sysfs vbuildersysfs ${BUILD_ROOT}${fs}
	    ;;
	/proc)
	    [ -d ${BUILD_ROOT}${fs} ] || mkdir -p ${BUILD_ROOT}${fs}
	    [ -z "$(mount | grep ${BUILD_ROOT}${fs})" ] && \
		mount -o _netdev -t proc vbuilderproc ${BUILD_ROOT}${fs}
	    ;;
	/dev/shm)
	    [ -d ${BUILD_ROOT}${fs} ] || mkdir -p ${BUILD_ROOT}${fs}
	    [ -z "$(mount | grep ${BUILD_ROOT}${fs})" ] && \
		mount -o _netdev -t tmpfs vbuildertmpfs ${BUILD_ROOT}${fs}
	    ;;
	/dev/pts)
	    [ -d ${BUILD_ROOT}${fs} ] || mkdir -p ${BUILD_ROOT}${fs}
	    [ -z "$(mount | grep ${BUILD_ROOT}${fs})" ] && \
		mount -o gid=5,mode=620,_netdev -t devpts vbuilderdevpts ${BUILD_ROOT}${fs}
	    ;;
	vfs)
	    for dir in /dev /dev/pts /dev/shm /proc /sys; do
	    	mount-chroot-mount ${dir} || return 1
	    done
	    ;;
	archives_dir)
	    [ -d ${EXTERNAL_ARCHIVES_DIR} ] || mkdir -p ${EXTERNAL_ARCHIVES_DIR}
	    [ -d ${ARCHIVES_DIR} ] || mkdir -p ${ARCHIVES_DIR}
	    [ -z "$(mount | grep ${ARCHIVES_DIR})" ] && \
		mount --bind -o _netdev ${EXTERNAL_ARCHIVES_DIR} ${ARCHIVES_DIR}
	    [ -d ${ARCHIVES_DIR}/partial ] || mkdir -p ${ARCHIVES_DIR}/partial
	    ;;
	unionfs_dir)
	    if [ $with_unionfs -eq 1 ]; then
		[ -d ${UNIONFS_ROOT} ] || mkdir -p ${UNIONFS_ROOT}
		if ( /sbin/modprobe aufs >& /dev/null ) ; then
		    [ -z "$(mount | grep ${UNIONFS_ROOT})" ] && \
		        mount -t aufs -o br=${UNIONFS_ROOT}=rw:${BUILD_ROOT}=ro aufs ${BUILD_ROOT}
		else
		    [ -z "$(mount | grep ${UNIONFS_ROOT})" ] && \
		        mount -t unionfs -o dirs=${UNIONFS_ROOT}=rw:${BUILD_ROOT}=ro unionfs ${BUILD_ROOT}
		    unionctl ${BUILD_ROOT} --list
		fi
	    fi
	    ;;
	*)
	    echo mount-chroot-mount: unknown file system $fs
	    exit 1
	    ;;
    esac
    return 0
}

### end of file