#!/bin/sh

# truncate mountpoint to work around 88 char mount limit on FreeBSD
__hack88_mount () {
    local _altroot _exportvar _fulluuid _shortuuid _mountpoint _mount_len \
          _hack88 _dataset _template _jail_zfs_dataset_re _set _tag

    _altroot="$(zpool get -H altroot ${pool} | awk '{print $3}')"
    _fulluuid="$1"
    _dataset="$2"
    _exportvar="$3"
    _shortuuid="$(echo ${_fulluuid}|cut -f1 -d\-)"
    _mountpoint="$(__get_jail_prop mountpoint ${_fulluuid} ${_dataset})"
    _template="$(__get_jail_prop istemplate ${_fulluuid} ${_dataset})"
    _hack88="$(__get_jail_prop hack88 ${_fulluuid} ${_dataset})"
    _tag="$(__get_jail_prop tag ${_fulluuid} ${_dataset})"
    _jail_zfs_dataset_re="^($(echo $(__get_jail_prop jail_zfs_dataset \
        "${_fulluuid}" "${_dataset}") \
        | tr -s '[:space:]' '|' | sed -e 's/\|*$//'))"
    _mount_len="$(echo ${_mountpoint} | sed  s#.*jails.#''# | wc -c)"
    _set=0

    if [ "${_hack88}" = "1" ] && [ "${_mount_len}" -eq "37" ] && [ "${_template}" = "no" ]; then
        __unlink_tag $_dataset
        echo "  INFO: truncating jail mountpoint"
        zfs umount -f "${iocroot}/jails/${_fulluuid}"
        zfs set mountpoint="${iocroot}/jails/${_shortuuid}" "${_dataset}"
        zfs list -rH -o name "${pool}/iocell/jails/${_fulluuid}" | \
            egrep -v "${_jail_zfs_dataset_re}" | xargs -L 1 zfs mount
        __link_tag "${_dataset}" "${_tag}"

        if [ ! -z "${_exportvar}" ] ; then
            export ${_exportvar}=${_shortuuid}
            _set=1
        fi
    elif [ "${_hack88}" != "1" ] && [ "${_mount_len}" -lt "37" ] && [ "${_template}" = "no" ] ; then
        __unlink_tag "${_dataset}"
        echo "  INFO: restoring jail mountpoint"
        zfs umount -f "${iocroot}/jails/${_shortuuid}"
        zfs set mountpoint="${iocroot}/jails/${_fulluuid}" "${_dataset}"
        zfs list -rH -o name "${pool}/iocell/jails/${_fulluuid}" | \
            egrep -v "${_jail_zfs_dataset_re}" | xargs -L 1 zfs mount
        __link_tag "${_dataset}" "${_tag}"

        if [ ! -z "${_exportvar}" ] ; then
            export ${_exportvar}=${_fulluuid}
            _set=1
        fi
    fi

    # Needed if we did no operations at all for create
    if [ ! -z "${_exportvar}" -a "${_set}" -eq 0 ] ; then
        if [ "${_hack88}" != "1" ] ; then
            export ${_exportvar}=${_fulluuid}
        else
            export ${_exportvar}=${_shortuuid}
        fi
    fi
}
