#!/bin/bash

LOG_DIR="/config/logs"
DB_FILE="/config/db/atlas.db"
NMAP_LOG="$LOG_DIR/nmap.log"
HOSTS_LOG="$LOG_DIR/hosts.log"

mkdir -p "$LOG_DIR"

uname -a > "$LOG_DIR/uname.log"
ip -o -f inet addr show > "$LOG_DIR/ip.log"
arp -a > "$LOG_DIR/arp.log"
df -h > "$LOG_DIR/df.log"

SUBNET=$(ip -o -f inet addr show | awk '/scope global/ {split($4,a,"/"); print a[1]"/24"; exit}')

# Enhanced scan with open ports, OS, and MAC
nmap -O -sS "$SUBNET" -oG "$NMAP_LOG"

# Parse all enriched fields from nmap output
awk '
/^Host:/ {ip=$2; name=($3=="Status:" ? "NoName" : $3); data[ip]["name"]=name}
/Ports:/ {data[ip]["ports"]=$2}
/OS details:/ {gsub("OS details: ", "", $0); data[ip]["os"]=$0}
/MAC Address:/ {gsub(/^.*MAC Address: /,"",$0); split($0,a," "); data[ip]["mac"]=a[1]}
END {
  for (ip in data) {
    print ip, data[ip]["name"], data[ip]["mac"], data[ip]["ports"], data[ip]["os"]
  }
}' "$NMAP_LOG" > "$HOSTS_LOG"

# Insert/update records
while IFS= read -r ip name mac_address open_ports os_details; do
    next_hop=""
    network_name=""

    existing=$(sqlite3 "$DB_FILE" "SELECT COUNT(*) FROM hosts WHERE ip = '$ip';")

    if [ "$existing" -eq 0 ]; then
        sqlite3 "$DB_FILE" <<EOF
INSERT INTO hosts (ip, name, os_details, mac_address, open_ports, next_hop, network_name, last_seen)
VALUES ('$ip', '$name', '$os_details', '$mac_address', '$open_ports', '$next_hop', '$network_name', CURRENT_TIMESTAMP);
EOF
    else
        # Fetch old values
        read old_mac old_ports old_os <<< $(sqlite3 "$DB_FILE" "SELECT mac_address, open_ports, os_details FROM hosts WHERE ip = '$ip';")

        # Retain previous values if new values are missing
        [ -z "$mac_address" ] || [ "$mac_address" == "Unknown" ] && mac_address="$old_mac"
        [ -z "$open_ports" ] || [ "$open_ports" == "Unknown" ] && open_ports="$old_ports"
        [ -z "$os_details" ] || [ "$os_details" == "Unknown" ] && os_details="$old_os"

        sqlite3 "$DB_FILE" <<EOF
UPDATE hosts
SET name = '$name',
    os_details = '$os_details',
    mac_address = '$mac_address',
    open_ports = '$open_ports',
    next_hop = '$next_hop',
    network_name = '$network_name',
    last_seen = CURRENT_TIMESTAMP
WHERE ip = '$ip';
EOF
    fi
done < "$HOSTS_LOG"

# Delete stale entries
current_ips=$(awk '{print $1}' "$HOSTS_LOG" | sort | uniq | tr '\n' ',' | sed 's/,$//')
sqlite3 "$DB_FILE" <<EOF
DELETE FROM hosts WHERE ip NOT IN ($(echo "'$current_ips'" | sed "s/,/','/g"));
EOF

echo "✅ Scan complete — database updated with enriched values."
