#!/bin/sh

# ugly: this variable is set during port install time
ezjail_prefix=EZJAIL_PREFIX
ezjail_etc=${ezjail_prefix}/etc
ezjail_share=${ezjail_prefix}/share/ezjail
ezjail_examples=${ezjail_prefix}/share/examples/ezjail
ezjail_jailcfgs=${ezjail_etc}/ezjail

# read user config
[ -f ${ezjail_etc}/ezjail.conf ] && . ${ezjail_etc}/ezjail.conf

# set defaults
ezjail_jaildir=${ezjail_jaildir:-"/usr/jails"}
ezjail_jailtemplate=${ezjail_jailtemplate:-"${ezjail_jaildir}/newjail"}
ezjail_jailbase=${ezjail_jailbase:-"${ezjail_jaildir}/basejail"}
ezjail_jailfull=${ezjail_jailfull:-"${ezjail_jaildir}/fulljail"}
ezjail_flavours=${ezjail_flavours:-"${ezjail_jaildir}/flavours"}
ezjail_sourcetree=${ezjail_sourcetree:-"/usr/src"}
ezjail_portscvsroot=${ezjail_portscvsroot:-":pserver:anoncvs@anoncvs.at.FreeBSD.org:/home/ncvs"}

ezjail_mount_enable=${ezjail_mount_enable:-"YES"}
ezjail_devfs_enable=${ezjail_devfs_enable:-"YES"}
ezjail_devfs_ruleset=${ezjail_devfs_ruleset:-"devfsrules_jail"}
ezjail_procfs_enable=${ezjail_procfs_enable:-"YES"}
ezjail_fdescfs_enable=${ezjail_fdescfs_enable:-"YES"}

# define our bail out shortcut
exerr () { echo -e "$*"; exit 1; }

# check for command
[ $1 ] || exerr "Usage: `basename -- $0` [create|delete|list|update] {params}"

case "$1" in
######################## ezjail-admin CREATE ########################
create)
  shift
  args=`getopt xf:r: $*` || exerr "Usage: `basename -- $0` create [-f flavour] [-r jailroot] [-x] jailname jailip"

  newjail_root=
  newjail_flavour=
  newjail_softlink=
  newjail_fill="YES"

  set -- ${args}
  for arg do
    case ${arg} in
      -x) newjail_fill="NO"; shift;;
      -r) newjail_root="$2"; shift 2;;
      -f) newjail_flavour="$2"; shift 2;;
      --) shift; break;;
    esac
  done
  newjail_name=$1; newjail_ip=$2

  # we need at least a name and an ip for new jail
  [ "${newjail_name}" -a "${newjail_ip}" -a $# = 2 ] || exerr "Usage: `basename -- $0` create [-f flavour] [-r jailroot] [-x] jailname jailip"

  # check, whether ezjail-update has been called. existence of 
  # ezjail_jailbase is our indicator
  [ -d ${ezjail_jailbase} ] || exerr "Error: base jail does not exist. Please run 'ezjail-admin update' first."

  # relative paths don't make sense in rc.scripts
  [ ${ezjail_jaildir%%[!/]*} ] || exerr "Error: Need an absolute path in ezjail_jaildir, it currently is set to: ${ezjail_jaildir}."

  # jail names must not irritate file systems, excluding dots from this list
  # was done intentionally to permit foo.com style directory names, however,
  # the jail name will be foo_com in most scripts

  newjail_name=`echo -n ${newjail_name} | tr /~ __`
  newjail_nname=`echo -n "${newjail_name}" | tr -c [:alnum:] _`
  newjail_root=${newjail_root:-"${ezjail_jaildir}/${newjail_name}"}

  # jail names may lead to identical configs, eg. foo.bar.com == foo-bar.com
  # so check, whether we might be running into problems
  [ -e ${ezjail_jailcfgs}/${newjail_nname} ] && exerr "Error: an ezjail config already exists at ${ezjail_jailcfgs}/${newjail_nname}. Please rename the ezjail."

  # if jail root specified on command line is not absolute, make it absolute
  # inside our jail directory
  [ ${newjail_root%%[!/]*} ] || newjail_root=${ezjail_jaildir}/${newjail_root}

  # if jail root specified on command line does not lie within our jail 
  # directory, we need to create a softlink
  if [ "${newjail_root##${ezjail_jaildir}}" = "${newjail_root}" ]; then
    newjail_softlink=${ezjail_jaildir}/`basename -- ${newjail_root}`
    [ -e ${newjail_softlink} -a "${newjail_fill}" = "YES" ] && exerr "Error: an ezjail already exists at ${newjail_softlink}."
  fi

  # do some sanity checks on the selected flavour (if any)
  [ "${newjail_flavour}" -a ! -d ${ezjail_flavours}/${newjail_flavour} ] && exerr "Error: Flavour config directory ${ezjail_flavours}/${newjail_flavour} not found."

  #
  # All sanity checks that may lead to errors are hopefully passed here
  #

  # now take a copy of our template jail
  if [ "${newjail_fill}" = "YES" ]; then
    mkdir -p ${newjail_root} && cd ${ezjail_jailtemplate} && \
    find * | cpio -p -v ${newjail_root} > /dev/null
    [ $? = 0 ] || exerr "Error: Could not copy template jail."
  fi

  # if a soft link is necessary, create it now
  [ ${newjail_softlink} ] && ln -s ${newjail_root} ${newjail_softlink}

  # if the automount feature is not disabled, this fstab entry for new jail
  # will be obeyed
  echo ${ezjail_jailbase} ${newjail_root}/basejail nullfs ro 0 0 > /etc/fstab.${newjail_nname}

  # now, where everything seems to have gone right, create control file in 
  # ezjails config dir
  mkdir -p ${ezjail_jailcfgs}
  echo export jail_${newjail_nname}_hostname=\"${newjail_name}\"  > ${ezjail_jailcfgs}/${newjail_nname}
  echo export jail_${newjail_nname}_ip=\"${newjail_ip}\"  >> ${ezjail_jailcfgs}/${newjail_nname}
  echo export jail_${newjail_nname}_rootdir=\"${newjail_root}\"  >> ${ezjail_jailcfgs}/${newjail_nname}
  echo export jail_${newjail_nname}_exec=\"/bin/sh /etc/rc\"  >> ${ezjail_jailcfgs}/${newjail_nname}
  echo export jail_${newjail_nname}_mount_enable=\"${ezjail_mount_enable}\"  >> ${ezjail_jailcfgs}/${newjail_nname}
  echo export jail_${newjail_nname}_devfs_enable=\"${ezjail_devfs_enable}\"  >> ${ezjail_jailcfgs}/${newjail_nname}
  echo export jail_${newjail_nname}_devfs_ruleset=\"devfsrules_jail\"  >> ${ezjail_jailcfgs}/${newjail_nname}
  echo export jail_${newjail_nname}_procfs_enable=\"${ezjail_procfs_enable}\"  >> ${ezjail_jailcfgs}/${newjail_nname}
  echo export jail_${newjail_nname}_fdescfs_enable=\"${ezjail_fdescfs_enable}\" >> ${ezjail_jailcfgs}/${newjail_nname}

  # Final steps for flavour installation
  if [ ${newjail_flavour} ]; then
    # install files and config to new jail
    cd ${ezjail_flavours}/${newjail_flavour}
    find * | cpio -p -v ${newjail_root} > /dev/null

    # If a config is found, make it auto run on jails startup
    if [ -f ${newjail_root}/ezjail.flavour ]; then
      ln -s /ezjail.flavour ${newjail_root}/etc/rc.d/ezjail-config.sh
      chmod 0700 ${newjail_root}/ezjail.flavour
      echo "Note: Shell scripts installed, flavourizing on jails first startup."
    fi
  fi

  # For user convenience some scenarios commonly causing headaches are checked

  # check, whether IP is configured on a local interface, warn if it isnt
  ping -c 1 -m 1 -t 1 -q ${newjail_ip} > /dev/null
  [ $? = 0 ] || echo "Warning: IP ${newjail_ip} not configured on a local interface."

  # check, whether some host system services do listen on the Jails IP
  TIFS=${IFS}; IFS=_
  newjail_listener=`sockstat -4 -l | grep ${newjail_ip}:[[:digit:]]`
  [ $? = 0 ] && echo -e "Warning: Some services already seem to be listening on IP ${newjail_ip}\n  This may cause some confusion, here they are:\n${newjail_listener}"

  newjail_listener=`sockstat -4 -l | grep \*:[[:digit:]]`
  [ $? = 0 ] && echo -e "Warning: Some services already seem to be listening on all IP, (including ${newjail_ip})\n  This may cause some confusion, here they are:\n${newjail_listener}"
  IFS=${TIFS}

  ;;
######################## ezjail-admin DELETE ########################
delete)
  shift
  args=`getopt w $*` || exerr "Usage: `basename -- $0` delete [-w] jailname"

  oldjail_wipe=

  set -- ${args}
  for arg do
    case ${arg} in
      -w) oldjail_wipe="YES"; shift;;
      --) shift; break;;
    esac
  done
  oldjail_name=$1

  # we only need name of jail to vanish
  [ "${oldjail_name}" -a $# = 1 ] || exerr "Usage: `basename -- $0` delete [-w] jailname"

  # tidy up jail name the ezjail way
  oldjail_nname=`echo -n ${oldjail_name} | tr -c [:alnum:] _`

  # check for existence of jail in our records
  [ -f ${ezjail_jailcfgs}/${oldjail_nname} ] || exerr "Error: Nothing known about jail ${oldjail_name}."

  # fetch information about the jail to be gone by parsing our records
  . ${ezjail_jailcfgs}/${oldjail_nname}
  eval oldjail_rootdir=\"\$jail_${oldjail_nname}_rootdir\"

  # if jail is still running, refuse to go any further
  [ -f /var/run/jail_${oldjail_nname}.id ] && exerr "Error: Jail appears to be still running, stop it first.\n(/var/run/jail_${oldjail_nname}.id exists)."

  # now we know everything we need to let the jail be gone remove entry 
  # from ezjail resource structure, delete fstab.JAILNAME
  rm -f ${ezjail_jailcfgs}/${oldjail_nname}
  rm -f /etc/fstab.${oldjail_nname}

  # if there is a soft link pointing to the jail root, remove it
  oldjail_softlink=${ezjail_jaildir}/`basename ${oldjail_rootdir}`
  [ -L ${oldjail_softlink} ] && rm ${oldjail_softlink}

  # if wiping the jail was requested, remove it
  [ ${oldjail_wipe} ] && rm -rf ${oldjail_rootdir}

  ;;
######################## ezjail-admin LIST ########################
list)
  jail_list=`ls ${ezjail_jailcfgs}`
  for jail in ${jail_list}; do
    . ${ezjail_jailcfgs}/${jail}
    eval jail_ip=\"\$jail_${jail}_ip\"
    eval jail_hostname=\"\$jail_${jail}_hostname\"
    eval jail_rootdir=\"\$jail_${jail}_rootdir\"
    printf "%-15s %-28s %s\\n" ${jail_ip} ${jail_hostname} ${jail_rootdir}
  done

  ;;
######################## ezjail-admin UPDATE ########################
setup|update)
  shift
  args=`getopt ipPs: $*` || exerr "Usage: `basename -- $0` update [-s sourcetree] [-i] [-pP]"

  updatejail_installaction="world"
  updatejail_provideports=

  set -- ${args}
  for arg do
    case ${arg} in
      -i) updatejail_installaction="installworld"; shift;;
      -s) ezjail_sourcetree="$2"; shift 2;;
      -p) updatejail_provideports="YES"; shift;;
      -P) updatejail_provideports="YES"; updatejail_installaction="none"; shift;;
      --) shift; break;;
    esac
  done

  if [ "${updatejail_installaction}" = "none" ]; then
    # check, whether ezjail-update has been called. existence of 
    # ezjail_jailbase is our indicator
    [ -d ${ezjail_jailbase} ] || exerr "Error: base jail does not exist. You cannot fill base jails ports tree before creating it. Please run 'ezjail-admin update' first."
  else
    # Bump the user for some of the most common errors
    [ -d ${ezjail_sourcetree} ] || exerr "Cannot find your copy of the FreeBSD source tree in ${ezjail_sourcetree}."
    [ -e ${ezjail_sourcetree}/Makefile ] || exerr "Your source tree in ${ezjail_sourcetree} seems to be incomplete (Makefile missing)."

    # Normally fulljail should be renamed by past ezjail-admin commands.
    # However those may have failed
    chflags -R noschg ${ezjail_jailfull}; rm -rf ${ezjail_jailfull};
    mkdir -p ${ezjail_jailfull}

    # make our world
    cd ${ezjail_sourcetree}
    make ${updatejail_installaction} DESTDIR=${ezjail_jailfull} || exerr "make ${updatejail_installaction} failed."

    # setup world
    make distribution DESTDIR=${ezjail_jailfull} || exerr "make distribution failed."

    # Fill basejail from installed world
    cd ${ezjail_jailfull}
    # This mkdir is important, since cpio will create intermediate
    # directories with permission 0700 which is bad
    mkdir -p ${ezjail_jailbase}/usr
    for dir in bin lib libexec sbin usr/bin usr/include usr/lib usr/libexec usr/sbin usr/src usr/share; do
      find ${dir} | cpio -d -p -v ${ezjail_jailbase} || exerr "Installation of ${dir} failed."
      chflags -R noschg ${dir}; rm -r ${dir}; ln -s /basejail/${dir} ${dir}
    done
    mkdir basejail

    # Try to remove the old template jail
    if [ -d ${ezjail_jailtemplate} ]; then
      if [ -d ${ezjail_jailtemplate}_old ]; then
        chflags -R noschg ${ezjail_jailtemplate}_old
        rm -rf ${ezjail_jailtemplate}_old
      fi
      mv ${ezjail_jailtemplate} ${ezjail_jailtemplate}_old
    fi
    mv ${ezjail_jailfull} ${ezjail_jailtemplate}

    # If the default flavour example has not yet been copied, do it now
    [ -d ${ezjail_flavours}/default ] || mkdir -p ${ezjail_flavours} && cp -p -R ${ezjail_examples}/default ${ezjail_flavours}

  fi # installaction="none"

  # The user may want to have a ports tree in basejail
  if [ "${updatejail_provideports}" = "YES" ]; then
    # if /usr/ports/CVS exists, assume cvs up is safe
    if [ -f ${ezjail_jailbase}/usr/ports/CVS/Root ]; then
      echo -n "Updating ports from "; cat ${ezjail_jailbase}/usr/ports/CVS/Root
      echo "Gathering local information may take a while."
      cd ${ezjail_jailbase}/usr/ports/; cvs -d ${ezjail_portscvsroot} up -Pd
    else
      echo "Checking out ports from ${ezjail_portscvsroot}"
      mkdir -p ${ezjail_jailbase}/usr/ports/
      cd ${ezjail_jailbase}/usr/; cvs -d ${ezjail_portscvsroot} co ports
    fi
    [ $? = 0 ] || exerr "Updating ports failed."
  fi

  # A ports collection inside jails is hardly useful w/o an appropriate
  # /etc/make.conf. If we find basejail/usr/ports/Makefile, assume that
  # the admin wants a working make.conf in new jails also a softlink to 
  # the ports in basejail is provided
  if [ -f ${ezjail_jailbase}/usr/ports/Makefile ]; then
    # no /usr/ports? link to /basejail/usr/ports
    [ -e ${ezjail_jailtemplate}/usr/ports ] || ln -s /basejail/usr/ports ${ezjail_jailtemplate}/usr/ports

    if [ -f ${ezjail_examples}/default/etc/make.conf -a ! -f ${ezjail_jailtemplate}/etc/make.conf ]; then
      cp -p ${ezjail_examples}/default/etc/make.conf ${ezjail_jailtemplate}/etc/
      echo "Note: a non-standard /etc/make.conf was copied to the template jail in order to get the ports collection running inside jails."
    fi
  fi

  ;;
*)
  exerr "Usage: `basename -- $0` [create|delete|list|update] {params}"
  ;;
esac