#!/bin/sh
#
# destroy an existing jail

JAIL_NAME=$1
JAIL_PATH=$2
PREFIX=/usr/local
JLS_NAME="/usr/sbin/jls name"
JLS_PATH="/usr/sbin/jls path"
PLATFORM=${PREFIX}/bastille
FSTAB_PATH=${PLATFORM}/fstab/$1.fstab
JAIL_PATH=${PLATFORM}/jails/$1

if [ $# -lt 2 ]; then
    echo "Required: name path."
    return 1
fi

if [ ! -d ${JAIL_PATH} ]; then
    echo "Path (${JAIL_PATH}) not found."
    return 1
fi

if [ $(${JLS_NAME} | grep ${JAIL_NAME}) ]; then
    echo "Jail is running."
    echo "Stop jail first with bbsd-stop ${JAIL_NAME}."
    return 1
fi

if [ $(${JLS_PATH} | grep ${JAIL_PATH}) ]; then
    echo "Jail is running."
    echo "Stop jail first with bbsd-stop ${JAIL_NAME}."
    return 1
fi

if [ -d ${JAIL_PATH} ]; then
    zfs destroy -r zroot${JAIL_PATH} || echo "Unable to destroy zroot${JAIL_PATH}."
    rm -rf ${JAIL_PATH} || echo "Unable to delete ${JAIL_PATH}."
    echo "Jail destroyed. RIP."
fi
