#!/bin/bash

# Copyright © 2019 Le Filament (<http://www.le-filament.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

PROGNAME=$(basename $0)

STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2

INVERSE=0

FSTAB_STATUS=0
MOUNTED_STATUS=0

MOUNTS=/proc/mounts
MTAB=/etc/mtab
FSTAB=/etc/fstab

function usage() {
        echo "Usage: $PROGNAME \$mountpoint [\$mountpoint2 ...]"
        echo "Usage: $PROGNAME -h,--help"
        echo "Options:"
        echo " -I          Inverse results (OK if not mounted, WARNING if mounted)"
        echo " MOUNTPOINT  list of mountpoint to check. MANDATORY"
}

function print_help() {
        echo ""
        echo "This module checks if a mountpoint is defined in ${FSTAB}, and whether it is mounted"
        echo "by checking ${MTAB}, ${MOUNTS} and mountpoint program"
        echo ""
        usage
        echo ""
}

# --------------------------------------------------------------------
# startup checks
# --------------------------------------------------------------------

if [ $# -eq 0 ]; then
        usage
        exit $STATE_CRITICAL
fi

while [ "$1" != "" ]
do
        case "$1" in
                -I) INVERSE=1; shift;;
                /*) MP="$1"; shift;;
                *) usage; exit $STATE_UNKNOWN;;
        esac
done

if [ -z "${MP}" ]; then
        echo "ERROR: no mountpoint given!"
        usage
        exit $STATE_UNKNOWN
fi

## check FSTAB mounts
if [ ! -z "$( grep ${MP} ${FSTAB} )" ]
then
    FSTAB_STATUS=1
fi

# check MOUNTS mounts
if [ ! -z "$( grep ${MP} ${MOUNTS} )" ]
then
    # check MTAB mounts
    if [ ! -z "$( grep ${MP} ${MTAB} )" ]
    then
        ## check mountpoint
        if [ $( mountpoint -q ${MP} ; echo $? ) -eq 0 ]
        then
            MOUNTED_STATUS=1
        fi
    fi
fi

if [ $MOUNTED_STATUS -eq 0 ]
then
    if [ $INVERSE -eq 0 ]
    then
        echo "CRITICAL: ${MP} not mounted"
        exit $STATE_CRITICAL
    else
        echo "OK: ${MP} not mounted"
        exit $STATE_OK
    fi
else
    if [ $FSTAB_STATUS -eq 0 ]
    then
        echo "WARNING: ${MP} mounted but not defined in fstab"
        exit $STATE_WARNING
    else
        if [ $INVERSE -eq 0 ]
        then
            echo "OK: ${MP} mounted"
            exit $STATE_OK
        else
            echo "WARNING: ${MP} mounted"
            exit $STATE_WARNING
        fi
    fi
fi
