#!/bin/bash
# iTechSmart Pulse Scanner — macOS
# Double-click to run in Terminal

cd "$(dirname "$0")"

PURPLE='\033[95m'
GREEN='\033[92m'
YELLOW='\033[93m'
RED='\033[91m'
BOLD='\033[1m'
END='\033[0m'

echo -e "${PURPLE}${BOLD}"
cat << 'BANNER'
  ██╗████████╗███████╗ ██████╗██╗  ██╗
  ██║╚══██╔══╝██╔════╝██╔════╝██║  ██║
  ██║   ██║   █████╗  ██║     ███████║
  ██║   ██║   ██╔══╝  ██║     ██╔══██║
  ██║   ██║   ███████╗╚██████╗██║  ██║
  ╚═╝   ╚═╝   ╚══════╝ ╚═════╝╚═╝  ╚═╝
  ███████╗███╗   ███╗ █████╗ ██████╗ ████████╗
  ██╔════╝████╗ ████║██╔══██╗██╔══██╗╚══██╔══╝
  ███████╗██╔████╔██║███████║██████╔╝   ██║
  ╚════██║██║╚██╔╝██║██╔══██║██╔══██╗   ██║
  ███████║██║ ╚═╝ ██║██║  ██║██║  ██║   ██║
  ╚══════╝╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝
BANNER
echo -e "${END}"
echo -e "  ${BOLD}iTechSmart Pulse — macOS Security Scanner${END}"
echo -e "  Powered by iTechSmart UAIO Platform"
echo "  ──────────────────────────────────────────"
echo ""

# Check Python3
if ! command -v python3 &>/dev/null; then
    echo -e "  ${YELLOW}!${END}  Python3 not found"
    echo "  Opening Python download page..."
    open "https://www.python.org/downloads/"
    read -p "  Install Python3 then press Enter..."
fi

echo -e "  ${GREEN}+${END}  Python3 ready"
echo ""

# Download Mac scanner
TMPFILE=$(mktemp /tmp/pulse_XXXXXX.py)

curl -sSL \
  "https://app.itechsmart.dev/download/pulse-mac-script" \
  -o "$TMPFILE"

if [ -s "$TMPFILE" ]; then
    python3 "$TMPFILE"
else
    # Fallback: embedded macOS scanner
    echo -e "  ${YELLOW}!${END}  Download failed, running embedded scanner..."
    python3 << 'PYSCAN'
import sys, os, json, hashlib, platform, subprocess, socket
from datetime import datetime, timezone

PURPLE='\033[95m'; GREEN='\033[92m'; YELLOW='\033[93m'; RED='\033[91m'; BOLD='\033[1m'; END='\033[0m'

def ok(msg): print(f"  {GREEN}+{END}  {msg}")
def warn(msg): print(f"  {YELLOW}!{END}  {msg}")

print(f"\n  {PURPLE}{BOLD}Pulse{END} Security Scanner v1.1.1")
print(f"  {'_'*42}\n")

hostname = socket.gethostname()
ok(f"Host:  {hostname}")
ok(f"OS:    macOS {platform.mac_ver()[0]} {platform.machine()}")
ok(f"CPUs:  {os.cpu_count() or 0}")

checks = []
print(f"\n  {PURPLE}{BOLD}[2]{END} Running security checks...")

# Gatekeeper
try:
    r = subprocess.run(["spctl", "--status"], capture_output=True, text=True, timeout=5)
    if "enabled" in r.stdout.lower() or "enabled" in r.stderr.lower():
        checks.append({"name": "Gatekeeper", "status": "pass", "detail": "Enabled"})
    else:
        checks.append({"name": "Gatekeeper", "status": "warn", "detail": "Disabled"})
except Exception:
    checks.append({"name": "Gatekeeper", "status": "unknown", "detail": "Could not check"})

# Firewall
try:
    r = subprocess.run(["/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate"],
                       capture_output=True, text=True, timeout=5)
    if "enabled" in r.stdout.lower():
        checks.append({"name": "Firewall", "status": "pass", "detail": "Application firewall ON"})
    else:
        checks.append({"name": "Firewall", "status": "warn", "detail": "Application firewall OFF"})
except Exception:
    checks.append({"name": "Firewall", "status": "unknown", "detail": "Could not check"})

# FileVault
try:
    r = subprocess.run(["fdesetup", "status"], capture_output=True, text=True, timeout=5)
    if "On" in r.stdout:
        checks.append({"name": "FileVault", "status": "pass", "detail": "Disk encryption ON"})
    else:
        checks.append({"name": "FileVault", "status": "warn", "detail": "Disk encryption OFF"})
except Exception:
    checks.append({"name": "FileVault", "status": "unknown", "detail": "Could not check"})

# Software Updates
try:
    r = subprocess.run(["softwareupdate", "-l"], capture_output=True, text=True, timeout=30)
    if "No new software available" in r.stderr or "No new software available" in r.stdout:
        checks.append({"name": "Updates", "status": "pass", "detail": "Up to date"})
    else:
        checks.append({"name": "Updates", "status": "warn", "detail": "Updates available"})
except Exception:
    checks.append({"name": "Updates", "status": "pass", "detail": "Could not check"})

for c in checks:
    (ok if c["status"] == "pass" else warn)(f"{c['name']}: {c['detail']}")

passed = sum(1 for c in checks if c["status"] == "pass")
total = len(checks)
ratio = passed / total if total else 0
grade = "A" if ratio >= 0.9 else "B" if ratio >= 0.75 else "C" if ratio >= 0.6 else "D" if ratio >= 0.4 else "F"

scan = {"hostname": hostname, "os": f"macOS {platform.mac_ver()[0]} {platform.machine()}", "grade": grade,
        "checks_passed": passed, "checks_total": total, "checks": checks,
        "timestamp": datetime.now(timezone.utc).isoformat()}
receipt_hash = hashlib.sha256(json.dumps(scan, sort_keys=True).encode()).hexdigest()

gc = {**dict.fromkeys(["A","B"], GREEN), **dict.fromkeys(["C"], YELLOW), **dict.fromkeys(["D","F"], RED)}.get(grade, GREEN)
print(f"\n  {'='*40}\n")
print(f"  {BOLD}SCAN RESULTS{END}\n  {'_'*40}")
print(f"  Grade:    {gc}{BOLD} {grade} {END}")
print(f"  Passed:   {passed}/{total} checks")
print(f"  Host:     {hostname}")
print(f"\n  {BOLD}RECEIPT{END}\n  {'_'*40}")
print(f"  Hash:  {BOLD}{receipt_hash}{END}")
print(f"\n  Verify: {GREEN}{BOLD}https://itechsmart.dev/verify?hash={receipt_hash[:16]}{END}")
print(f"\n  {'='*40}\n")
print(f"  {GREEN}{BOLD}Scan complete!{END} Powered by {PURPLE}iTechSmart UAIO{END}\n")
PYSCAN
fi

rm -f "$TMPFILE"

echo ""
echo -e "  ${BOLD}Press Enter to close...${END}"
read
