#! /usr/bin/env python3.12

import scapy.all as scapy
import json
import socket

def scan(ip):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
    results = []
    for element in answered_list:
        result = {"ip": element[1].psrc, "mac": element[1].hwsrc, 'hostname': socket.gethostbyaddr(element[1].psrc)[0]}
        results.append(result)  
    return results


def test_port(address: str, dest_port: int) -> bool:
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            if sock.connect_ex((address, dest_port)) == 0:
                return True
        return False
    except (OSError, ValueError):
        return False



def create_ip_list(target_ip="192.168.50.1/24"):
    only_ip_list = []
    for i in scan(target_ip):
        #print(test_port(address=i['ip'], dest_port=22))
        if i['hostname'] != ".":
            only_ip_list.append(i['hostname'])
        else:
            only_ip_list.append(i['ip']) 
    return only_ip_list

def scan_csv(csv_file=str):
    pass


if __name__ == "__main__":
    ip_list = create_ip_list()

    output = {
        "_meta": {
         "hostvars": {
                "webprod": {
                    "http_port": 123, 
                    }
        }
    },
    "network-scan": {
        "hosts": ip_list,
        "vars": {
                    "ansible_user": "jonnybravo",
                    "ansible_python_interpreter": "/usr/bin/python3", 
                    "ansible_ssh_private_key_file": "/home/jonnybravo/.ssh/ansible-test"
                    }
    }
}
    print(json.dumps(output,indent=4, sort_keys=True))


