import psutil
import smtplib
from email.mime.text import MIMEText
import requests
import socket

# Configuration
mountPoints = ["/", "/home/subdomains"]  # Specify mount points to monitor
threshold = 80  # Percentage threshold
emailSettings = {
    "sender": "cameron@livetimelapse.com.au",
    "receivers": ["ben@livetimelapse.com.au", "cameron@livetimelapse.com.au"],
    "smtpServer": "smtp.gmail.com",
    "smtpPort": 587,
    "username": "cameron@livetimelapse.com.au",
    "password": "TimeLapseIT123!",
}
googleChatWebhook = "https://chat.googleapis.com/v1/spaces/AAAAFTd8QvU/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=ttouDjQlgMlZc5v_nqq7UdhmOzm2v1BaP5PpPuxKRuI"

def sendEmail(server, mountPoint, usagePercent):
    try:
        subject = f"Disk Usage Alert: {server}"
        body = f"Warning! The disk usage on {server} for mount point {mountPoint} is {usagePercent}%."
        msg = MIMEText(body)
        msg["Subject"] = subject
        msg["From"] = emailSettings["sender"]
        msg["To"] = ", ".join(emailSettings["receivers"])

        with smtplib.SMTP(emailSettings["smtpServer"], emailSettings["smtpPort"]) as server:
            server.starttls()
            server.login(emailSettings["username"], emailSettings["password"])
            server.send_message(msg)
            print(f"Email sent successfully for {mountPoint}")
    except Exception as e:
        print(f"Error sending email: {e}")

def sendGoogleChatMessage(server, mountPoint, usagePercent):
    try:
        message = {
            "text": f"Warning! The disk usage on {server} for mount point {mountPoint} is {usagePercent}%."
        }
        response = requests.post(googleChatWebhook, json=message)
        if response.status_code == 200:
            print(f"Google Chat message sent successfully for {mountPoint}")
        else:
            print(f"Failed to send Google Chat message: {response.text}")
    except Exception as e:
        print(f"Error sending Google Chat message: {e}")

def checkMountPoints():
    server = socket.gethostname()
    for mountPoint in mountPoints:
        usage = psutil.disk_usage(mountPoint)
        usagePercent = usage.percent
        if usagePercent >= threshold:
            print(f"High usage detected on {mountPoint}: {usagePercent}%")
            sendEmail(server, mountPoint, usagePercent)
            sendGoogleChatMessage(server, mountPoint, usagePercent)

if __name__ == "__main__":
    checkMountPoints()
