import re
import json
import collections
from tomark import Tomark
from datetime import datetime
from collections import Counter
# require install tomark
# https://pypi.org/project/tomark/
NMAP_SCRIPT = "scripts/identify-attack-surface-from-nmap-scan.py"
MD_FILE = "docs/9-PORTS_INDEX.md"
MD_FILE_TPL = f"""
> **Note**: ðŸ•’ Updated on %s

ðŸ“– [Source](../{NMAP_SCRIPT}).

%s
"""
# Extract the services mapping dict from the script "identify-attack-surface-from-nmap-scan.py"
with open(NMAP_SCRIPT, mode="r", encoding="utf-8") as f:
    content = f.read()
    data = re.findall(r'SERVICES_MAPPING\s*=\s*(\{[a-z0-9\s\[\]"/:,_-]+\})', content, re.MULTILINE | re.IGNORECASE)[0]
    data = json.loads(data)
# Generate the index
data = collections.OrderedDict(sorted(data.items()))
table_data = []
list_ports = []
for srv_name, srv_ports in data.items():
    srv_ports.sort()
    list_ports.extend(srv_ports)
    ports = str(srv_ports).strip("[]").replace(" ", "")
    table_data.append({"Service type": srv_name.title(), "Ports": ports})
port_occurences = Counter(list_ports)
for port, occurence in port_occurences.items():
    if occurence > 1:
        raise Exception(f"Port {port} is present {occurence} times!")    
markdown_code = Tomark.table(table_data)
now = datetime.now()
ctime = now.strftime("%Y-%m-%d at %H:%M:%S")
content = MD_FILE_TPL % (ctime, markdown_code)
with open(MD_FILE, mode="w", encoding="utf-8") as f:
    f.write(content)
