#!/bin/bash

# ==============================================================================
# Ghaymah Systems - Automated Security Baseline Checker
# Description: Validates Permissions, Open Ports, and SSL Configuration.
# ==============================================================================

# Output Colors for readability
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

DOMAIN="ghaymah.systems"

echo -e "${YELLOW}====================================================${NC}"
echo -e "${YELLOW}       Ghaymah Systems - Security Audit Script      ${NC}"
echo -e "${YELLOW}====================================================${NC}\n"

# ------------------------------------------------------------------------------
# 1. PERMISSIONS CHECK (صلاحيات)
# Ensures the script/container is not running with root privileges (Rule 2.2)
# ------------------------------------------------------------------------------
echo -e "[1] Checking System Permissions (Least Privilege / Rootless)..."
if [ "$EUID" -eq 0 ]; then
  echo -e "  ${RED}[FAILED]${NC} Environment is running as root (UID 0). This violates Ghaymah's rootless container policy."
else
  echo -e "  ${GREEN}[PASSED]${NC} Environment is running as a non-root user (UID $EUID)."
fi
echo ""

# ------------------------------------------------------------------------------
# 2. PORTS CHECK (منافذ)
# Checks if SSH (Port 22) is actively listening, which should be disabled (Rule 3.1)
# ------------------------------------------------------------------------------
echo -e "[2] Checking Exposed Ports (Zero Trust Network)..."
# Using 'ss' or 'netstat' to check for port 22 listening state
if command -v ss &> /dev/null; then
    PORT_CHECK=$(ss -tuln | grep -E ':(22)\s')
elif command -v netstat &> /dev/null; then
    PORT_CHECK=$(netstat -tuln | grep -E ':(22)\s')
else
    PORT_CHECK="Command not found, skipping."
    echo -e "  ${YELLOW}[WARNING]${NC} Neither 'ss' nor 'netstat' is installed to check ports."
fi

if [[ -n "$PORT_CHECK" && "$PORT_CHECK" != "Command not found, skipping." ]]; then
  echo -e "  ${RED}[FAILED]${NC} Unauthorized open port detected (Port 22/SSH is listening)!"
  echo "$PORT_CHECK"
elif [[ "$PORT_CHECK" == "" ]]; then
  echo -e "  ${GREEN}[PASSED]${NC} No unauthorized management ports (like SSH) are exposed."
fi
echo ""

# ------------------------------------------------------------------------------
# 3. SSL/TLS CERTIFICATE CHECK (SSL)
# Checks if the target domain has a valid, non-expired SSL certificate (Rule 3.3/4.1)
# ------------------------------------------------------------------------------
echo -e "[3] Checking SSL Certificate Validity for $DOMAIN..."
if command -v openssl &> /dev/null; then
    # Fetch the expiration date of the SSL certificate
    EXPIRATION_DATE=$(echo | openssl s_client -servername "$DOMAIN" -connect "$DOMAIN":443 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)
    
    if [ -n "$EXPIRATION_DATE" ]; then
        # Convert dates to seconds since epoch for comparison
        EXP_SECONDS=$(date -d "$EXPIRATION_DATE" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRATION_DATE" +%s)
        CURRENT_SECONDS=$(date +%s)
        
        if [ "$EXP_SECONDS" -lt "$CURRENT_SECONDS" ]; then
            echo -e "  ${RED}[FAILED]${NC} The SSL certificate for $DOMAIN has EXPIRED on $EXPIRATION_DATE."
        else
            echo -e "  ${GREEN}[PASSED]${NC} SSL Certificate is valid. Expires on: $EXPIRATION_DATE."
        fi
    else
        echo -e "  ${RED}[FAILED]${NC} Could not retrieve SSL certificate. Is the domain reachable over port 443?"
    fi
else
    echo -e "  ${YELLOW}[WARNING]${NC} 'openssl' command is not installed. Cannot verify SSL."
fi

echo -e "\n${YELLOW}====================================================${NC}"
echo -e "${YELLOW}                  Audit Complete                    ${NC}"
echo -e "${YELLOW}====================================================${NC}"