#!/bin/bash

# Email configuration
recipient="arunkumars@schemaxtech.com"
subject="Service Status Alert of SA_Dev Server"
mail_body="Verified all services of SA_Dev server services running status"

# Function to check service status and append to mail if service is not running
check_service_status() {
  service_name=$1
  if systemctl is-active --quiet "$service_name"; then
    echo "$service_name is running"
  else
    echo "$service_name is not running"
    mail_body="${mail_body}
	
	${service_name} service is not running.\n"
  fi
}

# Check Apache2 status
echo "Checking Apache2 status..."
check_service_status apache2

# Check MariaDB status (or MySQL, depending on your system)
echo "Checking mysql status..."
check_service_status mysql

# Check pm2 status
echo "Checking pm2 status..."
if pm2 status >/dev/null 2>&1; then
  echo "pm2 services are running"
else
  echo "pm2 services are not running"
  mail_body="${mail_body}pm2 services are not running.\n"
fi

# Check disk space usage
echo "Checking disk space usage:"
threshold=10  # Threshold for free space (in %)
df_output=$(df -h | grep '/dev/sd')

echo "$df_output"

# Check if disk space is below the threshold (example: 10% free space)
echo "$df_output" | while read -r line; do
  use_percent=$(echo "$line" | awk '{print $5}' | sed 's/%//')
  
  # Check if the extracted value is a valid number
  if [[ "$use_percent" =~ ^[0-9]+$ ]]; then
    if [ "$use_percent" -ge $((100 - threshold)) ]; then
      mail_body="${mail_body}Warning: Disk space usage is above $((100 - threshold))%. Details:\n$line\n"
    fi
  fi
done

# Output the mail body to see what will be sent (for debugging)
echo -e "Mail body content:\n$mail_body"

# Send mail alert if there are issues
if [ -n "$mail_body" ]; then
  echo "Sending alert email..."
  echo -e "Subject: $subject\n\n$mail_body" | msmtp "$recipient"
else
  echo "All services are running fine, and disk space is under control."
fi
