#!/bin/bash
#
# This program will generate initial root based on required and
# base packages's Priority field.
# It is tightly integreated into Debian bootstrapping technology.
#
# It uses three main components:
#    1) apt
#    2) debarchiver
#    3) debootstrap
#
# Therefore it is required those packages to be pre-installed.
# Apt repository is also required.
#
##############################################################################

#
# Copyright (C) 2005-2012 Nexenta Systems, Inc.
# All rights reserved.
#
##############################################################################

#set -x

test ! -f /etc/nbld.cf && echo "Error: can't find /etc/nbld.cf" && exit 1
. /etc/nbld.cf

repo="$NBLD_REPO"		        # APT repository (must exist)
repolock="$repo/dists/debarchiver.lock" # APT debarchiver's lock
dist="$NBLD_DISTRO-$NBLD_BRANCH"	# IN repository's distribution name
rootdir="$NBLD_MINIROOT"                # bootstrap output
#hddrepo="/usr/illumian"	        	# APT repository for HDD mode
hddrepo="/usr/instarch"	        	# APT repository for HDD mode
customdir="$NBLD_LIBDIR"	        # directory with data files
extra_dir="/var/lib/nbld"		# directory with extra data files
debug="$NBLD_DEBUG"		        # default no debug mode
mode="$NBLD_DEFAULT_MODE"	        # no default mode
install_script=distr-install.sh
install_profile="$rootdir$hddrepo/defaults"
pkglist="$NBLD_TMP/debootstrap-pkglist.tmp"

product_title="NexentaOS"
release_file="release.txt"
apt_sources="http://apt.gnusolaris.org elatte-testing main contrib non-free"

# do not show license by default
ks_license_text=""

profile0="minimal"
lines0="1800"
desc0="Recommended for advanced users only"
longdesc0="Minimal profile will setup a bare minimum Console-only NexentaOS system which later could be customized by using dselect/apt-get utilities."
rootsize0="512"

profile1="desktop"
lines1="4200"
desc1="Recommended for most users setups"
longdesc1="Desktop profile will setup typical desktop system with GNOME. Desktop profile is recommended option."
rootsize1="2048"

profiles="0 1"
defprofile="1"

usage() {
	cat << EOF
Usage: nbld-bootstrap [--rootdir dir] [--debug] [--repo dir] [--dist name]
EOF
	exit 1
}
fatal() { echo "Error: $1"; exit 1; }
cleanup() { 
#	if test "x$repolock_set" = xyes; then rmdir $repolock 2>/dev/null;
#	repolock_set=no; echo "Lock $repolock removed"; fi; 
	echo "OK"
	umount /etc/mnttab 2>/dev/null
}
trap "cleanup" INT EXIT TERM QUIT

UUID=`id -u`
#if [ `whoami` != "root" ]; then
if [ $UUID != "0" ]; then
	echo "Insufficient privileges to run $0"
	exit 1
fi

while test "x$1" != x; do
	if test "x$1" = "x--debug"; then debug=yes;
	elif test "x$1" = "x--repo"; then repo=$2; shift;
	elif test "x$1" = "x--dist"; then dist=$2; shift;
	elif test "x$1" = "x--rootdir"; then rootdir=$2; shift;
	elif test "x$1" = "x--help" -o "x$1" = "x-h"; then usage;
	else usage; fi
	shift
done

# Recalculate some globals
repolock="$repo/dists/debarchiver.lock"
install_profile="$rootdir$hddrepo/defaults"
environ="$rootdir /usr/bin/env -i PATH=usr/gnu/bin:/usr/bin:/sbin:/usr/sbin LOGNAME=root HOME=/root TERM=xterm "

if mount | grep $rootdir 1>/dev/null 2>&1 && test -d $rootdir; then
	echo "Error: $rootdir is busy. has loopback mounted dirs."
	exit 1
fi

test -d $rootdir && umount $rootdir/proc 2>/dev/null

if test -f $customdir/$mode.profile; then
	. $customdir/$mode.profile
elif test -f $mode.profile; then
	. $mode.profile
else
	echo "Error: $mode.profile not found."
	exit 1
fi

cat << EOF
==============================================================================
Mode:       ${mode}
Repository: ${repo} (${dist})
Fakeroot:   ${rootdir}
==============================================================================
EOF

echo -n "Live-CD/DVD mode is "
if test "x$mode_type" = xlivecd; then
	echo "ON"
else
	echo "OFF"
fi

echo -n "Generic install mode is "
if test "x$mode_type" = xinstall; then
	echo "ON"
else
	echo "OFF"
fi

echo "Selected Mode is $mode"
export BOOTSTRAP_EXTRA_DEBS="$LOCAL_ARCHIVE_DEBS ${REQ_DEBS}"
export STAGE0_DEBS="$STAGE0_DEBS ${REQ_DEBS} $STAGE0_APTINST $STAGE0_CD $STAGE0_DRIVERS $STAGE0_CD_END $STAGE0_HDD_END"

# From now on selected do 'install' or 'livecd' type
mode=$mode_type

echo -n "Debug mode is "
if test "x$debug" = xyes; then
	echo "ON"
else
	echo "OFF"
fi

echo "Cleaning up $rootdir ... "
test -d $rootdir && rm -rf $rootdir
mkdir -p $rootdir

APT_GET="apt-get -R $rootdir"

if test "x$mode" = xinstall; then
cat << EOF
------------------------------------------------------------------------------
Generating InstallCD filelist...
------------------------------------------------------------------------------
EOF
#export BOOTSTRAP_REQUIRED="sunwcsd sunwcs bash dpkg"

#echo "$APT_GET update"
#$APT_GET update
#echo "$APT_GET $APT_GET install -d -y --force-yes $BOOTSTRAP_REQUIRED"
#$APT_GET install -d -y --force-yes $BOOTSTRAP_REQUIRED

cat << EOF
------------------------------------------------------------------------------
Downloading package archive...
------------------------------------------------------------------------------
EOF
BOOTSTRAP_REQUIRED="$BOOTSTRAP_REQUIRED $STAGE0_DEBS"

echo "$APT_GET update"
$APT_GET update
echo "$APT_GET install -d -y --force-yes $BOOTSTRAP_REQUIRED"
$APT_GET install -d -y --force-yes $BOOTSTRAP_REQUIRED

	echo $BOOTSTRAP_REQUIRED > /tmp/required-$profile1.lst
	echo $BOOTSTRAP_BASE > /tmp/base-$profile1.lst
#	cp $rootdir/debootstrap/debpaths /tmp
#	mv $rootdir/var/cache/apt/archives $rootdir/var/cache/stage0_archive
#	rm -rf $rootdir/var/cache/apt
#	rm -rf $rootdir/debootstrap
	export BOOTSTRAP_EXTRA_DEBS="$STAGE0_DEBS"
fi

cat << EOF
------------------------------------------------------------------------------
Generating a $profile0 profile filelist... 
------------------------------------------------------------------------------
EOF

cat << EOF
------------------------------------------------------------------------------
Generating a $mode-mode  filelist... 
------------------------------------------------------------------------------
EOF

cat << EOF
------------------------------------------------------------------------------
Bootstrapping $mode CD media... 
------------------------------------------------------------------------------
EOF

if test "x$mode" = xinstall ; then
	echo "Creating local repository... "
	test -d $rootdir$hddrepo || mkdir -p $rootdir$hddrepo
	test -d $rootdir$hddrepo/conf || mkdir -p $rootdir$hddrepo/conf

	repopro="$rootdir$hddrepo/conf/distributions"
	echo "Origin: $NBLD_DISTRO" > $repopro
	echo "Label: $NBLD_DISTRO" >> $repopro
	echo "Suite: $NBLD_BRANCH" >> $repopro
	echo "Codename: $NBLD_DISTRO-$NBLD_BRANCH" >> $repopro
	echo "Architectures: $NBLD_ARCH" >> $repopro
	echo "Components: main contrib non-free" >> $repopro
	echo "Contents: . .gz .bz2" >> $repopro
	echo "ContentsArchitectures: $NBLD_ARCH" >> $repopro
	echo "ContentsComponents: main contrib non-free" >> $repopro
	echo "DscIndices: Sources Release .gz .bz2" >> $repopro
	echo "DebIndices: Packages Release . .gz .bz2" >> $repopro
	echo "Description: $NBLD_DISTRO platform" >> $repopro
	echo "SignWith: 16E16062" >> $repopro

	echo "Propagating local repository... "
	find $rootdir -name "*.deb" | \
	    xargs reprepro -Vb $rootdir$hddrepo --export=never includedeb $NBLD_DISTRO-$NBLD_BRANCH

	echo "Finalizing local repository... "
	reprepro -Vb $rootdir$hddrepo export
	rm -rf $rootdir$hddrepo/conf
	rm -rf $rootdir$hddrepo/db

	echo "Copying pre-generated filelists... "
#	mv /tmp/required-$profile1.lst $rootdir$hddrepo
#	mv /tmp/base-$profile1.lst $rootdir$hddrepo
#	mv /tmp/required-$profile0.lst $rootdir$hddrepo
#	mv /tmp/base-$profile0.lst $rootdir$hddrepo
	rm -f $install_profile
	test "x$ks_scripts" != x && cat $customdir/$ks_scripts >> $install_profile
	echo "_KS_product_title='$product_title'" >> $install_profile
	for p in $profiles; do
		eval "echo \"_KS_profile_name[$p]='\$profile$p'\"" >> $install_profile
		eval "echo \"_KS_profile_lines[$p]='\$lines$p'\"" >> $install_profile
		eval "echo \"_KS_profile_desc[$p]='\$desc$p'\"" >> $install_profile
		eval "echo \"_KS_profile_longdesc[$p]='\$longdesc$p'\"" >> $install_profile
		eval "echo \"_KS_profile_rootsize[$p]='\$rootsize$p'\"" >> $install_profile
	done
	echo "_KS_profiles='$profiles'" >> $install_profile
	echo "grub_n_title='$grub_n_title'" >> $install_profile
	echo "grub_s_title='$grub_s_title'" >> $install_profile
	for i in $ks_ifaces; do
		eval "echo \"_KS_iface_ip[$i]='\$ks_iface_ip$i'\"" >> $install_profile
		eval "echo \"_KS_iface_mask[$i]='\$ks_iface_mask$i'\"" >> $install_profile
	done
	echo "_KS_ifaces='$ks_ifaces'" >> $install_profile
	echo "_KS_apt_name='$dist'" >> $install_profile
	echo "_KS_apt_sources='$apt_sources'" >> $install_profile
	test "x$plugin_sources" != x && echo "_KS_plugin_sources='$plugin_sources'" >> $install_profile
	echo "_KS_profile_selected='$defprofile'" >> $install_profile
	test "x$ks_root_passwd" != x && echo "_KS_root_passwd='$ks_root_passwd'" >> $install_profile
	test "x$ks_user_name" != x && echo "_KS_user_name='$ks_user_name'" >> $install_profile
	test "x$ks_user_passwd" != x && echo "_KS_user_passwd='$ks_user_passwd'" >> $install_profile
	test "x$ks_hostname" != x && echo "_KS_hostname='$ks_hostname'" >> $install_profile
	test "x$ks_domainname" != x && echo "_KS_domainname='$ks_domainname'" >> $install_profile
	test "x$ks_gateway" != x && echo "_KS_gateway='$ks_gateway'" >> $install_profile
	test "x$ks_dns1" != x && echo "_KS_dns1='$ks_dns1'" >> $install_profile
	test "x$ks_dns2" != x && echo "_KS_dns2='$ks_dns2'" >> $install_profile
	test "x$ks_use_dhcp" != x && echo "_KS_use_dhcp='$ks_use_dhcp'" >> $install_profile
	test "x$ks_use_ipv6" != x && echo "_KS_use_ipv6='$ks_use_ipv6'" >> $install_profile
	test "x$ks_use_grub_mbr" != x && echo "_KS_use_grub_mbr='$ks_use_grub_mbr'" >> $install_profile
	test "x$ks_welcome_head" != x && echo "_KS_welcome_head='$ks_welcome_head'" >> $install_profile
	test "x$ks_welcome_ks" != x && echo "_KS_welcome_ks='$ks_welcome_ks'" >> $install_profile
	test "x$ks_check_upgrade" != x && echo "_KS_check_upgrade='$ks_check_upgrade'" >> $install_profile
	test "x$ks_detect_removable" != x && echo "_KS_detect_removable='$ks_detect_removable'" >> $install_profile
	test "x$ks_auto_reboot" != x && echo "_KS_auto_reboot='$ks_auto_reboot'" >> $install_profile
	test "x$ks_time_zone" != x && echo "_KS_time_zone='$ks_time_zone'" >> $install_profile
	test "x$ks_kbd_type" != x && echo "_KS_kbd_type='$ks_kbd_type'" >> $install_profile
	test "x$ks_rootdisks" != x && echo "_KS_rootdisks='$ks_rootdisks'" >> $install_profile
	test "x$ks_rootdisk_type" != x && echo "_KS_rootdisk_type='$ks_rootdisk_type'" >> $install_profile
	test "x$ks_rootdisk_name" != x && echo "_KS_rootdisk_name='$ks_rootdisk_name'" >> $install_profile
	test "x$ks_min_mem_required" != x && echo "_KS_min_mem_required='$ks_min_mem_required'" >> $install_profile
	test "x$ks_autopart_export_home" != x && echo "_KS_autopart_export_home='$ks_autopart_export_home'" >> $install_profile
	test "x$ks_autopart_manual" != x && echo "_KS_autopart_manual='$ks_autopart_manual'" >> $install_profile
	test "x$ks_autopart_use_swap_zvol" != x && echo "_KS_autopart_use_swap_zvol='$ks_autopart_use_swap_zvol'" >> $install_profile
	test "x$ks_need_network" != x && echo "_KS_need_network='$ks_need_network'" >> $install_profile
	if test "x$ks_startup_wizard" != x; then
	        echo "_KS_startup_wizard='$ks_startup_wizard'" >> $install_profile
	        test "x$ks_show_wizard_license" != x && echo "_KS_show_wizard_license='$ks_show_wizard_license'" >> $install_profile
	fi
	if test "x$model_id" != x -a "x$model_name" != x; then
	        echo "package NZA::Model;" > /tmp/model.$$
	        echo "\$NZA::Model::ID='$model_id';" >> /tmp/model.$$
	        echo "\$NZA::Model::NAME='$model_name';" >> /tmp/model.$$
	        echo "\$NZA::Model::COMPANY_SNAME='$company_title';" >> /tmp/model.$$
	        echo "\$NZA::Model::PRODUCT_FAMILY='$product_title';" >> /tmp/model.$$
	        echo "1;" >> /tmp/model.$$
	        mv /tmp/model.$$ $rootdir$hddrepo/Model.pm
	        echo "_KS_model='Model.pm'" >> $install_profile
	fi
	if test "x$ks_machinesig" != x; then
		bin_dir="/usr/local/bin"
		if ! test -d $rootdir$bin_dir; then
			mkdir -p $rootdir$bin_dir
		fi
		cp $customdir/nabat-config $rootdir$bin_dir/nabat-config
		chmod 744 $rootdir$bin_dir/nabat-config
	fi
	if test "x$ks_license_text" != x; then
		if test -f $customdir/$ks_license_text; then
			cp $customdir/$ks_license_text $rootdir$hddrepo
			chmod 644 $rootdir$hddrepo/$ks_license_text
		fi
		echo "_KS_license_text='$ks_license_text'" >> $install_profile
	fi

	echo "Initial local repository APT update ... "

	FILESCD="$STAGE0_CD $STAGE0_DRIVERS $STAGE0_CD_END"

	$APT_GET update
	$APT_GET install -m -y --force-yes sunwcsd
	$APT_GET install -m -y --force-yes sunwcs bash dpkg system-kernel
	$APT_GET install -m -y --force-yes $FILESCD
	$APT_GET install -f -y --force-yes
	$APT_GET clean

	# save list of packages for APT installation
	echo "$STAGE0_APTINST $STAGE0_DRIVERS $STAGE0_HDD_END" > $rootdir$hddrepo/aptinst.lst

	echo "Preparing  files /etc/apt/sources.list ... "
#	echo "deb file:///usr/instarch/ $dist main contrib non-free" > $rootdir/etc/apt/sources.list

	echo "deb file://$hddrepo/ $dist main contrib non-free" > \
		$rootdir/etc/apt/sources.list
#	echo "deb-src file://$hddrepo/ $dist main contrib non-free" >> \
#		$rootdir/etc/apt/sources.list

	echo "Copy mdisco* files ... "
	cp $customdir/mdisco $rootdir$hddrepo
	cp $customdir/hwdisco.pl $rootdir$hddrepo/hwdisco
	cp $customdir/hddisco $rootdir$hddrepo

	echo "Copy additional files ... "
	cp $customdir/genuuid $rootdir/usr/sbin/
	cp $customdir/chpasswd $rootdir/usr/sbin/
	# fix chpasswd
	touch $rootdir/etc/login.defs

	echo "Preparing install scripts... "
	cp -f $customdir/$install_script $rootdir$hddrepo
	chmod 755 $rootdir$hddrepo/$install_script
	cp -f $customdir/eventhook $rootdir$hddrepo
	chmod 755 $rootdir$hddrepo/eventhook
	cp -f $customdir/nexenta-sysidtool* $rootdir$hddrepo
	chmod 755 $rootdir$hddrepo/nexenta-sysidtool*

	mv $rootdir/lib/svc/method/console-login $rootdir/lib/svc/method/console-login.unmodified
	cp -f $customdir/distr-console-login $rootdir/lib/svc/method/console-login

	cp -f $customdir/nexenta-tetris $rootdir/usr/bin/tetris
	chmod 755 $rootdir/usr/bin/tetris
	cp -f $customdir/distr-log $rootdir/usr/bin/install-log
	chmod 755 $rootdir/usr/bin/install-log
	cp -f $customdir/tail.pl $rootdir/usr/bin
	chmod 755 $rootdir/usr/bin/tail.pl
	screen_title="$product_title $os_version"
	test "x$sw_version" != "x" && screen_title="$screen_title, software $sw_version"
	cat << EOF > $rootdir/root/.screenrc
bindkey -k k1 select 1
bindkey -k k2 select 2
bindkey -k k3 select 3
startup_message off
sorendition 04
hardstatus lastline "%{kB} %w %= | $screen_title"
screen -t Installer 1 /usr/instarch/distr-install.sh
screen -t Shell     2
screen -t Log       3 /usr/bin/install-log
select 1
EOF
	chmod 644 $rootdir/root/.screenrc
	mv $rootdir/etc/syslog.conf $rootdir/etc/syslog.conf.unmodified
	cp -f $customdir/nexenta-syslog.conf $rootdir/etc/syslog.conf
	chmod 644 $rootdir/etc/syslog.conf
	test "x$release_file" != "x" && cp $customdir/$release_file $rootdir/etc/release
	chmod 444 $rootdir/etc/release
#        echo "export TERMINFO=/usr/gnu/share/terminfo" >> $rootdir/root/.bash_profile
#	echo "export TERM=xterm-color" >> $rootdir/root/.bash_profile

        cp -f $customdir/install-base.sh $rootdir$hddrepo/install-base.sh
	chmod 755 $rootdir$hddrepo/install-base.sh
	cp -f $customdir/${NBLD_DEFAULT_MODE}_hdd_grub-menu.txt $rootdir$hddrepo/hdd_grub-menu.txt
	sed -e "s/__autoversion__/$os_version, software $sw_version/" -i $rootdir$hddrepo/hdd_grub-menu.txt

else
	# LiveCD/DVD
	cat << EOF > $rootdir/etc/apt/sources.list
deb http://apt.gnusolaris.org elatte-testing main contrib non-free
deb-src http://apt.gnusolaris.org elatte-testing main contrib non-free
EOF
	for c in main contrib non-free; do
		list="$rootdir/var/lib/apt/lists/apt.gnusolaris.org_dists_elatte-unstable_${c}_binary-solaris-i386_Packages"
		if test -f $list; then
			mv $list $(echo $list|sed -e 's/unstable/testing/')
		else
			touch $(echo $list|sed -e 's/unstable/testing/')
		fi
	done
fi


echo "Polishing ... "

# special fix for bootstraping machine
for pid in `ps -ef | nawk '/devfsadmd/ {print $2}'`; do
	if pfiles $pid 2>/dev/null | grep $rootdir >/dev/null; then
		kill -9 $pid
		break
	fi
done
sleep 2
#umount $rootdir/devices

rm -f $rootdir/etc/zfs/zpool.cache

# Fixing shadow...
#chroot $environ pwconv
gsed -i -e "s/^root:\*:/root::/" $rootdir/etc/shadow
rm -f $rootdir/etc/shadow- $rootdir/etc/shadow.org $rootdir/etc/passwd.org
# Make sure no kernel/user logging goes to the /dev/console
gsed -i -e "/\/dev\/sysmsg/d" $rootdir/etc/syslog.conf
rm -f $rootdir/*.err
rm -f $rootdir/*.orig
rm -f $rootdir/core
find $rootdir/usr -type d -name ".svn" | xargs rm -rf
if test "x$debug" != xyes; then
	rm -f $rootdir/var/cache/apt/archives/*.deb
	rm -f $rootdir/var/cache/apt/*.bin
	latest_log=/tmp/debootstrap.log.latest.$$
	cp $rootdir/debootstrap/debootstrap.log $latest_log
	rm -rf $rootdir/debootstrap
else
	latest_log=/tmp/debootstrap.log.latest.$$
#	cp $rootdir/debootstrap/debootstrap.log $latest_log
#	rm -rf $rootdir/debootstrap
fi

# Cleanup logs and extra files
#rm -rf $rootdir/var/cache/debconf
#rm -rf $rootdir/var/log/bootstrap.log
rm -rf $rootdir/var/log/dpkg.log
###rm -rf $rootdir/var/lib/dpkg/info
rm -f $rootdir/var/cache/apt/archives/*.deb
rm -rf $rootdir/tmp/*
#echo "NOTE: log file saved at $latest_log"

crle -u -c $rootdir/var/ld/ld.config -l /lib:/usr/lib:/usr/gnu/lib
crle -64 -u -c $rootdir/var/ld/64/ld.config -l /lib/64:/usr/lib/64:/usr/gnu/lib/64

devfsadm -r $rootdir -u

#exit 0
###

#if test "x$mode" = xinstall; then
#	$customdir/../../bin/nbld-saferoot $rootdir$hddrepo || exit 1
#fi

echo "$product_title $sw_version $sw_description" > $rootdir/etc/issue

CWD=`dirname $0`
#$customdir/../../bin/nbld-livecd || exit 1
$CWD/nbld-livecd || exit 1
