#!/bin/bash
#
# License: Copyright 2012 SpinetiX S.A. This file is licensed
#          under the terms of the GNU General Public License version 2.
#          This program is licensed "as is" without any warranty of any
#          kind, whether express or implied.
#

# The bootcount location
BOOTCOUNT=/proc/bootcount

# The no reset indicator for the bootcount
BOOTCOUNT_NORESET=/var/run/bootcount-no-reset

# Checks if a mount point is in /etc/fstab and optionally has the given
# type, returns 0 if found with the given type, 1 otherwise.
# The arguments must be the mount point, not
# the device, and optionally the filesystem type.
# If a third argument is provided it is used as the file to use instead
# of /etc/fstab (e.g., /etc/mtab or /proc/mounts)
isinfstab()
{
    local match="${1%/}"
    local fsmatch="$2"
    local fstab="$3"
    [ -z "$fstab" ] && fstab=/etc/fstab
    local dev mpt fstype opts dump pass junk
    while read dev mpt fstype opts dump pass junk; do
	[ "$dev" = "" -o "$dev" = "#" ] && continue # comment or empty line
	[ -n "$fsmatch" ] && [ "$fstype" != "$fsmatch" ] && continue
	[ "$match" = "${mpt%/}" ] && return 0
    done < "$fstab"
    return 1
}

# Checks if a mount point is mounted and optionally has the given
# type, returns 0 if found with the given type, 1 otherwise.
# The arguments must be the mount point, not
# the device, and optionally the filesystem type.
ismounted()
{
    isinfstab "$1" "$2" /proc/mounts
}

# Cleans up a path under /var. All files under path (arg1) are removed
# at the exception of files which are part of packages. The /var/log/lastlog
# file is also truncated if the path is /var/log.
cleanvarpath()
{
    local path="$1"
    find "$path" -type f  \
	\! -path /var/log/wtmp \! -path /var/run/utmp \
	\! -path /var/log/lastlog -print0 | \
	xargs -0r rm -f --
    if [ "$path" = /var/log -o "$path" = /var/log/ ]; then
	# Truncate /var/log/lastlog
	if [ -s /var/log/lastlog ]; then
	    : > /var/log/lastlog
	else
	    : # nothing to do but return success
	fi
    fi
}

