#!/bin/sh
# Script to create a new jail based on given flags
#####################################################################

# Source our functions
PROGDIR="`pbreg get /PC-BSD/TheWarden/ProgDir`"

if [ -z "${PROGDIR}" ]
then
   echo "PROGDIR unset! Is The Warden installed properly?"
   exit 155
fi

# Source our variables
. ${PROGDIR}/conf/warden.conf


# Load our passed values
IP="${1}"
HOST="${2}"
SOURCE="${3}"
PORTS="${4}"
STARTUP="${5}"

if [ -z "$IP" -o -z "${HOST}" -o -z "$SOURCE" -o -z "${PORTS}" -o -z "${STARTUP}" ] 
then
  echo "ERROR: Missing required data!"
  exit 6
fi


JAILDIR="${JDIR}/${IP}"

if [ -e "${JAILDIR}" ]
then
  echo "ERROR: This Jail directory already exists!"
  exit 5
fi

echo "Building new Jail... Please wait..."
mkdir -p "${JAILDIR}"

echo "Installing world..."
tar cvf - -C ${WORLDDIR} . 2>/dev/null | tar xvf - -C "${JAILDIR}" 2>/dev/null
echo "Done"

echo "${HOST}" > ${JAILDIR}/etc/.wardenhost
echo "${IP}" > ${JAILDIR}/etc/.wardenip

if [ "$SOURCE" = "YES" ]
then
  echo "Installing source..."
  mkdir -p "${JAILDIR}/usr/src"
  tar cvf - -C ${WORLDSRC} . 2>/dev/null | tar xvf - -C "${JAILDIR}/usr/src" 2>/dev/null
  echo "Done"
fi

if [ "$PORTS" = "YES" ]
then
  echo "Installing ports..."
  mkdir -p "${JAILDIR}/usr/ports"
  tar cvf - -C ${PROGDIR}/ports . 2>/dev/null | tar xvf - -C "${JAILDIR}/usr/ports" 2>/dev/null
  echo "Done"
fi

# Create an empty fstab
touch "${JDIR}/${IP}/etc/fstab"

# Setup rc.conf
echo "portmap_enable=\"NO\"
sshd_enable=\"YES\"
sendmail_enable=\"NO\"
hostname=\"${HOST}\"
devfs_enable=\"YES\"
devfs_system_ruleset=\"devfsrules_common\"" > "${JDIR}/${IP}/etc/rc.conf"

# Create the host for this device
echo "# : src/etc/hosts,v 1.16 2003/01/28 21:29:23 dbaker Exp $
#
# Host Database
#
# This file should contain the addresses and aliases for local hosts that
# share this file.  Replace 'my.domain' below with the domainname of your
# machine.
#
# In the presence of the domain name service or NIS, this file may
# not be consulted at all; see /etc/nsswitch.conf for the resolution order.
#
#
::1                     localhost localhost.localdomain
127.0.0.1               localhost localhost.localdomain ${HOST}
${IP}			${HOST}" > "${JDIR}/${IP}/etc/hosts"

# Copy resolv.conf
cp /etc/resolv.conf "${JDIR}/${IP}/etc/resolv.conf"

if [ "$STARTUP" = "YES" ]
then
  touch "${JDIR}/${IP}/etc/.wardenautostart"
fi


echo "Success! Jail created at ${JDIR}/${IP}"

exit 0
