#!/bin/sh
# Make an inmate file from a configured directory
######################################################################

# 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

IDIR="$1"
IFILEDIR="$2"
PWD="`pwd`"

if [ ! -d "${IDIR}" ]
then
  echo "ERROR: Inmate directory does not exist: ${IDIR}!"
  exit 5
fi

chk=`echo "${IDIR}" | cut -c 1-1`
if [ "${chk}" != "/" ]
then
  IDIR="${PWD}/${IDIR}"
fi


# Make the inmate now
#####################################################################

# First lets check for the presence of the required files

# Check for conf/inmate-name
if [ -e "${IDIR}/conf/inmate-name" -a ! -z "`cat ${IDIR}/conf/inmate-name`" ]
then
  echo "Inmate Name: `cat ${IDIR}/conf/inmate-name`" 
else
  echo "Error: ${IDIR}/conf/inmate-name: Not Found" 
  exit 10
fi

# Check for conf/inmate-version
if [ -e "${IDIR}/conf/inmate-version" -a ! -z "`cat ${IDIR}/conf/inmate-version`" ]
then
  echo "Inmate Version: `cat ${IDIR}/conf/inmate-version`" 
else
  echo "Error: ${IDIR}/conf/inmate-version: Not Found" 
  exit 10
fi

# Touch the inmate-descr file, to make sure its created.
touch ${IDIR}/conf/inmate-descr

# Check for any scripts
if [ -e "${IDIR}/preinstall.sh" ]
then
  chmod 755 ${IDIR}/preinstall.sh
  echo "preinstall.sh: OK"
fi

if [ -e "${IDIR}/preinstall-ext.sh" ]
then
  chmod 755 ${IDIR}/preinstall-ext.sh
  echo "preinstall-ext.sh: OK"
fi


if [ -e "${IDIR}/postinstall.sh" ]
then
  chmod 755 ${IDIR}/postinstall.sh
  echo "postinstall.sh: OK"
fi

if [ -e "${IDIR}/postinstall-ext.sh" ]
then
  chmod 755 ${IDIR}/postinstall-ext.sh
  echo "postinstall-ext.sh: OK"
fi

if [ -e "${IDIR}/uninstall.sh" ]
then
  chmod 755 ${IDIR}/uninstall.sh
  echo "uninstall.sh: OK"
fi


echo -e "Creating inmate file...\c"

# Lets create the actual file now
mkdir .wdntmp 2>/dev/null
cd .wdntmp

cp ${IDIR}/conf/inmate-name .
# Set the File Name variable
FNAME="`cat ${IDIR}/conf/inmate-name | tr -d ' '`"

cp ${IDIR}/conf/inmate-version .
# Set our File Version variable
FVER="`cat ${IDIR}/conf/inmate-version | tr -d ' '`"

cp ${IDIR}/conf/inmate-descr .
echo "`uname -r | cut -d '-' -f 1`" > inmate-OS
echo "`uname -p`" > inmate-platform

# Create the header tarball
tar cvzf header.tgz --exclude header.tgz . 2>/dev/null

# Create our spacer
echo "
___INMATE_START___" > .spacer

# Create the lzma of the package
tar cvf - -C ${IDIR} . 2>/dev/null | lzma -z - >"pkg.lzma" 2>/dev/null

# Make the .wit file now
cat header.tgz .spacer pkg.lzma > ../${FNAME}${FVER}.wit

cd ..
rm -rf .wdntmp

echo -e "Done"

if [ ! -z "$IFILEDIR" ]
then
  mv "${FNAME}${FVER}.wit" ${IFILEDIR}/ 
  echo "Created: ${IFILEDIR}/${FNAME}${FVER}.wit"
else
  echo "Created: ${PWD}/${FNAME}${FVER}.wit"
fi

