#!/bin/sh
##
#  Korinf project
#
#  Login in chroot script
#
#  Copyright (c) Etersoft <http://etersoft.ru> 2005, 2006, 2007, 2009, 2011, 2013
#  Copyright (c) Vitaly Lipatov <lav@etersoft.ru> 2009, 2011, 2013
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published by
#  the Free Software Foundation, either version 3 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 Affero General Public License for more details.

#  You should have received a copy of the GNU Affero General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/korinf/common

kormod mount list

SUDO="sudo"
if [ $UID = "0" ]; then
	SUDO=""
fi

if [ -z "$1" ] ; then
	echo "Available systems list:"
	get_distro_list $(get_target_list)
	exit 0
fi

if [ -z "$1" ] ; then
	echo "Login in build chroot." >&2
	echo "Use --help for usage information" >&2
	exit 1
fi

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
	echo "Login in chrooted system"
	echo "Use: korlogin System/Version [-r] [command]" >&2
	echo "	run without params for get available systems"
	echo "	-r - login as root"
	exit 0
fi

[ "$1" = "-n" ] && { shift ; NETBUILD=1 ; } || NETBUILD=

SYS=$(get_real_target_dist $1) || exit
shift

USERCO=""
[ "$1" = "-r" ] && shift || USERCO="--user"
COMMANDTO="/bin/bash"

# FIXME: only for local
#if [ -n "$LOCALLINUXFARM" ] ; then
#test -r $LOCALLINUXFARM/$SYS/bin/bash || COMMANDTO=""
#fi

[ -n "$1" ] && COMMANDTO="$@"

# fills $BUILDARCH, $DISTRNAME, $DISTRVERSION
parse_dist_name $SYS

if [ "$DISTRNAME" = "ALTLinux" ] ; then
	echo "ALT Linux uses build process with hasher..."
	HSETARCH=
	[ "$BUILDARCH" = "$SYSARCH" ] || HSETARCH="setarch $BUILDARCH"
	HDIR="$($HSETARCH loginhsh -q -d -b $DISTRVERSION)"
	HPARAM=
	[ -d "$HDIR" ] || HPARAM="$HPARAM -i"
	[ "$USERCO" = "--user" ] || HPARAM="$HPARAM -o"
	docmd $HSETARCH loginhsh -b $DISTRVERSION $HPARAM
	exit
fi

echo
echo "############"
mount_linux $SYS $KORLOGINHOME || continue

export HOSTNAME=$SYS
export PS1="[\u@$SYS \W]\$"

run_in_chroot $USERCO "$COMMANDTO"

end_umount

