#!/bin/sh -e
#
# $Id: initroot,v 1.58 2004/08/08 09:44:10 ldv Exp $
# Copyright (C) 2003, 2004  Dmitry V. Levin <ldv@altlinux.org>
# 
# The initroot utility for the hasher project
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

if [ "$0" = ./initroot ]; then
	. ./functions
	hasher_dir="$(/bin/pwd)"
else
	. /usr/share/hasher/functions
fi

Usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
initroot - fills chroot with initial set of packages.

Usage: $PROG [options] <path-to-workdir>

<path-to-workdir> must be valid writable directory.

Valid options are:
  --no-cache                    do not use cache;
  --no-contents-indices         do not use content indices;
  --repackage-source            repackage source as well as binaries;
  --number=NUMBER               subconfig identifier;
  --hasher-priv-dir=DIR         hasher-priv directory;
  --nprocs=NUMBER               number of CPUs to use;
  --install-langs=LANGLIST      list of languages to install;
  --pkg-init-list=LIST          override default initial package file list;
  --pkg-build-list=LIST         override default build package file list;
  -q, --quiet                   try to be more quiet;
  -v, --verbose                 print a message for each action;
  -V, --version                 print program version and exit;
  -h, --help                    show this text.
EOF
	[ -n "$1" ] && exit "$1" || exit
}

TEMP=`getopt -n $PROG -o q,v,V,h -l no-cache,no-contents-indices,repackage-source,pkg-init-list:,pkg-build-list:,number:,hasher-priv-dir:,nprocs:,install-langs:,contents-index-all:,contents-index-bin:,quiet,verbose,help,version -- "$@"` || Usage
eval set -- "$TEMP"

no_cache=
no_contents_indices=
init_list='setup filesystem rpm fakeroot>=0:0.7.3'
build_list='basesystem rpm-build>=0:4.0.4-alt21 kernel-headers-common>=0:1.1.4-alt1 sisyphus_check>=0:0.7.3 time'
nprocs=
install_langs=all
repackage_source=
while :; do
	case "$1" in
		--no-cache) no_cache=1
			;;
		--no-contents-indices) no_contents_indices=1
			;;
		--repackage-source) repackage_source=1
			;;
		--number) shift; number="${1##-}"
			[ -z "$(printf %s "$number" |tr -d [0-9])" ] ||
				Fatal "--number: $number: invalid number."
			number="-$number"
			;;
		--nprocs) shift; nprocs="$1"
			[ -z "$(printf %s "$nprocs" |tr -d [0-9])" ] ||
				Fatal "--nprocs: $nprocs: invalid number."
			;;
		--install-langs) shift; install_langs="$1"
			;;
		--hasher-priv-dir) shift; hasher_priv_dir="$1"
			;;
		--pkg-init-list) shift; init_list="$1"
			;;
		--pkg-build-list) shift; build_list="$1"
			;;
		-q|--quiet) quiet=-q
			;;
		-v|--verbose) verbose=-v
			;;
		-V|--version) print_version initroot
			;;
		-h|--help) Usage 0
			;;
		--contents-index-all|--contents-index-bin) shift # obsolete
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done

# exactly one argument, please.
[ "$#" -eq 1 ] || Usage

set_workdir "$1"
shift

[ -d "$chroot" ] || Fatal "$chroot: cannot access chroot."
[ -d "$aptbox" ] || Fatal "$aptbox: cannot access aptbox."
[ -r "$APT_CONFIG" ] || Fatal "$APT_CONFIG: cannot access APT configuration."

mkdir -p -m700 $verbose cache
mkdir -p -m700 $verbose cache/chroot/{list,package}{,.new}
mkdir -p -m700 $verbose cache/contents/{list,index}{,.new}

check_helpers

ugid1="$("$getugid1" $number)" ||
	Fatal "getugid1 failed."
uid1="$(printf %s "$ugid1" |cut -d: -f1)"
gid1="$(printf %s "$ugid1" |cut -d: -f2)"

ugid2="$("$getugid2" $number)" ||
	Fatal "getugid2 failed."
uid2="$(printf %s "$ugid2" |cut -d: -f1)"
gid2="$(printf %s "$ugid2" |cut -d: -f2)"

[ -n "$nprocs" ] ||
	nprocs="$(N=`egrep -cs ^cpu[0-9]+ /proc/stat ||:`; [ "$N" -gt 0 ] 2>/dev/null && printf %s "$N" || echo 1)"

check_tty

. "$hasher_dir/cache_chroot"
. "$hasher_dir/cache_contents"

init_list=`printf %s "$init_list" |tr -s ',[:space:]' ' ' |sed -e 's/^ \+//;s/ \+$//'`
[ -n "$init_list" ] ||
	Fatal "initial package file list is empty, cannot setup chroot."

initlist="$(print_uris $init_list)" ||
	Fatal "failed to generate initial package file list."
[ -n "$initlist" ] &&
	Verbose "generated initial package file list." ||
	Fatal "failed to generate non-empty initial package file list; check your sources.list"

# reorder to get setup and filesystem first.
initlist="$(printf %s "$initlist" |grep '/setup[-_]' ||:)
$(printf %s "$initlist" |grep '/filesystem[-_]' ||:)
$(printf %s "$initlist" |egrep -v '/(setup|filesystem)[-_]' ||:)"
initlist="$(printf %s "$initlist" |grep -v '^$' ||:)"

if [ -z "$no_cache" ]; then
	printf %s "$initlist" >cache/chroot/list.new/init
	[ ! -s cache/chroot/list.new/init ] || echo >>cache/chroot/list.new/init
fi

build_list=`printf %s "$build_list" |tr -s ',[:space:]' ' ' |sed -e 's/^ \+//;s/ \+$//'`
if [ -n "$build_list" ]; then
	buildlist="$(print_uris $build_list)" ||
		Fatal "failed to generate build package file list."
	buildlist="$(
		printf %s\\n "$buildlist" |while read bp; do
			[ -n "$bp" ] || continue
			printf %s "$initlist" |grep -qs "^$bp\$" || printf %s\\n "$bp"
		done
	)"
	buildlist="$(printf %s "$buildlist" |grep -v '^$' ||:)"
	[ -n "$buildlist" ] &&
		Verbose "generated build package file list." ||
		Fatal "failed to generate non-empty build package file list; check your sources.list"
else
	Verbose "package file list for build is empty, bypassing."
	buildlist=
fi # $build_list

if [ -z "$no_cache" ]; then
	printf %s "$buildlist" >cache/chroot/list.new/build
	[ ! -s cache/chroot/list.new/build ] || echo >>cache/chroot/list.new/build
fi

check_chroot_cache

if [ -n "$no_cache" -o -n "$rebuild_chroot_cache" ]; then
	create_chroot
else
	unpack_chroot_cache
fi

# Prepare /proc and /sys for potential mount.
rmdir $verbose chroot/proc chroot/sys &&
mkdir -m755 $verbose chroot/proc chroot/sys &&
chgrp "$gid1" $verbose chroot/proc chroot/sys &&
	Verbose "prepared mount points." ||
	Fatal "failed to prepare mount points."

check_contents_cache

if [ -n "$no_cache" -o -n "$rebuild_contents_cache" ]; then
	create_contents
else
	unpack_contents_cache
fi

if [ -n "$build_list" ]; then
	# Create /dev/log.
	/usr/bin/mksock -m666 "$chroot/dev/log" ||
		Fatal "failed to create \`$chroot/dev/log' socket."

	# Create RPM build directory tree.
	cat >"$entry" <<__EOF__
$entry_header

mkdir $verbose -m700 -- "\$TMPDIR"
rpminit $verbose
cat >>/usr/src/.rpmmacros <<\EOF
%packager Automated package hasher <hasher@localhost>
%buildhost ${USER:-`id -nu`}.hasher.altlinux.org
%__BTE hasher
%__nprocs $nprocs
${contents_index_bin:+%_pkg_contents_index_bin /.host/contents_index_bin}
%_rpmbuild_clean 0
${repackage_source:+%_rpmbuild_packagesource 1}
EOF
__EOF__
	chmod 755 "$entry"

	wlimit_time_elapsed=60 wlimit_time_idle=60 wlimit_bytes_written=65536 \
	"$chrootuid2" $number "$chroot" /.host/entry &&
		Verbose "created RPM build directory tree." ||
		Fatal "failed to create RPM build directory tree."
fi # $build_list

purge_chroot_in
purge_chroot_out
