#!/bin/sh
#
# This file is part of OpenMediaVault.
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Volker Theile <volker.theile@openmediavault.org>
# @copyright Copyright (c) 2009-2012 Volker Theile
#
# OpenMediaVault is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# OpenMediaVault is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OpenMediaVault. If not, see <http://www.gnu.org/licenses/>.

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions

OMV_FSTAB_CONFIG=${OMV_FSTAB_CONFIG:-"/etc/fstab"}
OMV_FSTAB_SECTIONNAME=${OMV_FSTAB_SECTIONNAME:-"openmediavault"}

# Create list of mount entries stored in database. Take care about the order
# of lines, binds must be located at the end.
mntent=$(echo -n "# >>> [${OMV_FSTAB_SECTIONNAME}]\\\n"; xmlstarlet sel -t \
  -m "//system/fstab/mntent[not(contains(opts,'bind'))]" \
	-v "concat(fsname,' ',dir,' ',type,' ',opts,' ',freq,' ',passno)" \
	-i "position() != last()" -n -b \
  -b \
  -i "count(//system/fstab/mntent[contains(opts,'bind')]) > 0" -n -b \
  -m "//system/fstab/mntent[contains(opts,'bind')]" \
	-v "concat(fsname,' ',dir,' ',type,' ',opts,' ',freq,' ',passno)" \
	-i "position() != last()" -n -b \
  -b \
  ${OMV_CONFIG_FILE} | xmlstarlet unesc |
  while read fsname dir type opts freq passno; do
	  # Modify spec field if it contains a UUID
	  if omv_isfsuuid ${fsname}; then
		  fsname="UUID=${fsname}"
	  fi
	  echo -n "${fsname} ${dir} ${type} ${opts} ${freq} ${passno}\\\n"
  done; echo -n "# <<< [${OMV_FSTAB_SECTIONNAME}]")

# Append mount entries if not still present or replace existing entries.
if ! grep -E "^# >>> \[${OMV_FSTAB_SECTIONNAME}\]$" ${OMV_FSTAB_CONFIG} >/dev/null; then
	echo "${mntent}" >> ${OMV_FSTAB_CONFIG}
else
	sed -i "/# >>> \[${OMV_FSTAB_SECTIONNAME}\]/,/# <<< \[${OMV_FSTAB_SECTIONNAME}\]/ c ${mntent}" ${OMV_FSTAB_CONFIG}
fi
