#!/bin/sh
# Script to create a new jail
#####################################################################

# 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


cd ${PROGDIR}

# Prompt for an IP for this jail
dialog --title "The Warden" --inputbox "Please enter a IP address for this new jail:" 15 35 2>${ATMP}
IP=`cat ${ATMP}`
rm ${ATMP}

if [ -e "${JDIR}/${IP}" ]
then
   echo "ERROR: A jail with this IP already exists!"
   rtn
   exit 2
fi

# Do a sanity check on the IP address
check_ip $IP
if [ "$?" != "0" ]
then
   echo "ERROR: IP address is invalid!"
   rtn
   exit 2
fi

# Prompt for a hostname for this jail
dialog --title "The Warden" --inputbox "Please enter a Hostname for this jail:" 15 35 2>${ATMP}
HOST=`cat ${ATMP}`
rm ${ATMP}


# Include source?
dialog --title "The Warden" --yesno "Add FreeBSD system source to this jail?" 7 40
if [ "$?" = "0" ]
then
  SYSSOURCE="YES"
else
  SYSSOURCE="NO"
fi

# Include Ports?
dialog --title "The Warden" --yesno "Add ports tree to this jail?" 7 40
if [ "$?" = "0" ]
then
  PORTS="YES"
else
  PORTS="NO"
fi

# Start this jail at system boot?
dialog --title "The Warden" --yesno "Start Jail at bootup?" 7 40
if [ "$?" = "0" ]
then
  STARTUP="YES"
else
  STARTUP="NO"
fi


# Package set?
#dialog --title "The Warden" --checklist "Install a Pre-built package set?" 20 40 6 apache "Apache (Web Server)" off mysql "MySQL (Database)" off pgres "Postgres (Database)" off php "PHP (Web Scripting)" off 2>${ATMP}
#
#FILE="${ATMP}"
#cp ${FILE} ${FILE}.tmp
#sed 's/"//g' < ${FILE}.tmp > ${FILE}

# Save the list of packages
#PKGSET=`cat ${FILE}`
#rm ${FILE}

# Confirm this jail now
dialog --title "The Warden" --yesno "Create this jail?\n\n       IP: $IP\n Hostname: ${HOST}\n   Source: $SYSSOURCE\n    Ports: $PORTS\nAutostart: $STARTUP " 20 40 
if [ "$?" = "0" ]
then
   # Create the jail now
   ${PROGDIR}/scripts/backend/createjail.sh "${IP}" "${HOST}" "${SYSSOURCE}" "${PORTS}" "$STARTUP"
   if [ "$?" != "0" ]
   then
     echo "ERROR: Jail creation failed!"
     rtn
     exit 55
   fi

   # Now make the user set the password for this jail
   dialog --msgbox "You will now be prompted to set the root password for this jail. Please keep this in a safe place!" 10 30
   echo "#!/bin/sh
passwd
" > "${JDIR}/${IP}/.chpass.sh"
   chmod 755 "${JDIR}/${IP}/.chpass.sh"
   chroot "${JDIR}/${IP}" /.chpass.sh
   rm "${JDIR}/${IP}/.chpass.sh"

  #  Add a user?
  dialog --title "The Warden" --yesno "Add a user to this jail?" 7 40
  if [ "$?" = "0" ]
  then
   echo "#!/bin/sh
adduser
" > "${JDIR}/${IP}/.chpass.sh"
   chmod 755 "${JDIR}/${IP}/.chpass.sh"
   chroot "${JDIR}/${IP}" /.chpass.sh
   rm "${JDIR}/${IP}/.chpass.sh"
  fi


fi

rtn
