#!/bin/bash
#
# autoport-chroot
# (c) 2012-2013 by Silvan Calarco <silvan.calarco@mambasoft.it>
#
. /etc/sysconfig/autoport

CHROOT_TARGET=$1
shift
CHROOT_COMMAND=$@

function usage() {
   echo "\
$0
"$"Copyright (C) 2012 Silvan Calarco <silvan.calarco@mambasoft.it>""
"$"Released under the terms of the GNU GPL v3 license"
   echo "
"$"Enters autoport  chroot environment.""

"$"Usage"":
   $me chroot_target [command [args..]]
"
}

[ "$CHROOT_TARGET" ] || {
   usage
   exit 1
}

[ "`uname -m`" = "x86_64" ] && HOST_IS_X86_64=1

for i in `seq 0 ${#AUTOPORT_ARCH[*]}`; do
   [ "${AUTOPORT_CHROOT[$i]}" = "$CHROOT_TARGET" ] || continue

   if [ "$HOST_IS_X86_64" -a "${AUTOPORT_ARCH[$i]}" != "x86_64" ]; then
      CMD_PREFIX=linux32
   else
      CMD_PREFIX=
   fi
   if [ "$CHROOT_COMMAND" ]; then
      $CMD_PREFIX /usr/sbin/chroot /var/autoport/${AUTOPORT_CHROOT[$i]} su -l $SU_APPEND ${AUTOPORT_CHROOT_USER[$i]} -c "${CHROOT_COMMAND}"
   else
      echo "Entering ${AUTOPORT_CHROOT[$i]} autoport chroot environment"
      hostname=`hostname`
      grep $hostname /var/autoport/${AUTOPORT_CHROOT[$i]}/etc/hosts >/dev/null || {
         sed -i "s|\(^127.0.0.1[[:space:]]*\)|\1$hostname |" /var/autoport/${AUTOPORT_CHROOT[$i]}/etc/hosts
      }
      [ -e /var/autoport/${AUTOPORT_CHROOT[$i]}/etc/profile.d/autoport.sh ] || {
         echo "PS1='[\u@${AUTOPORT_CHROOT[$i]} \W]\$ '" > /var/autoport/${AUTOPORT_CHROOT[$i]}/etc/profile.d/autoport.sh
      }
      $CMD_PREFIX /usr/sbin/chroot /var/autoport/${AUTOPORT_CHROOT[$i]} su -l $SU_APPEND ${AUTOPORT_CHROOT_USER[$i]}
   fi
   exit 0
done

echo "$CHROOT_TARGET: undefined chroot target"
exit 1
