#!/bin/bash

# Copyright 2014-2023 Security Onion Solutions, LLC
#
# This program 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
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

. /usr/sbin/so-common

appliance_check() {
  {%- if salt['grains.get']('sosmodel', '') %}
  APPLIANCE=1
  {%- if grains['sosmodel'] in ['SO2AMI01', 'SO2GCI01', 'SO2AZI01'] %}
  exit 0
  {%- endif %}
  DUDEYOUGOTADELL=$(dmidecode |grep Dell)
  if [[ -n $DUDEYOUGOTADELL ]]; then
  APPTYPE=dell
  else
  APPTYPE=sm
  fi
  mkdir -p /opt/so/log/raid

  {%- else %}
  echo "This is not an appliance"
  exit 0
  {%- endif %}
}

check_nsm_raid() {
  PERCCLI=$(/opt/raidtools/perccli/perccli64 /c0/v0 show|grep RAID|grep Optl)
  MEGACTL=$(/opt/raidtools/megasasctl |grep optimal)

  if [[ $APPLIANCE == '1' ]]; then
    if [[ -n $PERCCLI ]]; then
      HWRAID=0
    elif [[ -n $MEGACTL ]]; then
      HWRAID=0
    else
      HWRAID=1
    fi

  fi

}

check_boss_raid() {
  MVCLI=$(/usr/local/bin/mvcli info -o vd |grep status |grep functional)

  if [[ -n $DUDEYOUGOTADELL ]]; then
    if [[ -n $MVCLI ]]; then
      BOSSRAID=0
    else
      BOSSRAID=1
    fi
  fi
}

check_software_raid() {
  if [[ -n $DUDEYOUGOTADELL ]]; then
    SWRC=$(grep "_" /proc/mdstat)

    if [[ -n $SWRC ]]; then
        # RAID is failed in some way
        SWRAID=1
    else
        SWRAID=0
    fi
  fi
}

# This script checks raid status if you use SO appliances

# See if this is an appliance

appliance_check
check_nsm_raid
check_boss_raid
{%- if salt['grains.get']('sosmodel', '') %}
{%- if grains['sosmodel'] in ['SOSMN', 'SOSSNNV'] %}
check_software_raid
{%- endif %}
{%- endif %}

if [[ -n $SWRAID ]]; then
  if [[ $SWRAID == '0' && $BOSSRAID == '0' ]]; then
    RAIDSTATUS=0
  else
    RAIDSTATUS=1
  fi
elif [[ -n $DUDEYOUGOTADELL ]]; then
  if [[ $BOSSRAID == '0' && $HWRAID == '0' ]]; then
    RAIDSTATUS=0
  else
    RAIDSTATUS=1
  fi
elif [[ "$APPTYPE" == 'sm' ]]; then
  if [[ -n "$HWRAID" ]]; then
    RAIDSTATUS=0
  else
    RAIDSTATUS=1
  fi
fi

echo "nsmraid=$RAIDSTATUS" > /opt/so/log/raid/status.log


