#! /usr/bin/env python3.12

import csv
import errno
import json
import os
import socket
import sys

import scapy.all as scapy


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 port_open(address: str, dest_port=22) -> bool:
    # result = sock.connect_ex(('ras-dan-01.local',22))
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.settimeout(5)
        result = sock.connect_ex((address, dest_port))
        if result == 0:
            return True
        else:
            return False


def scan_csv(csvfile=str, colm="hostname"):
    if os.path.exists(csvfile):
        hostlist = []
        with open(csvfile) as csv_file:
            csv_reader = csv.DictReader(csv_file, delimiter=",")
            for count, row in enumerate(csv_reader, 1):
                hostlist.append(row[colm])
    else:
        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), csvfile)
    return tuple(hostlist)


def create_ip_list(target_ip=["192.168.50.1/24"]):
    only_ip_list = []
    for ip_rage in target_ip:
        for i in scan(ip_rage):
            if i["hostname"] != ".":
                scan_name = i["hostname"]
            else:
                scan_name = i["ip"]

            # print(scan_name)
            # print(port_open(address=scan_name))
            if port_open(address=scan_name):
                only_ip_list.append(scan_name)

    return tuple(only_ip_list)


if __name__ == "__main__":
    # if len(sys.argv) == 1:
    ip_list = create_ip_list()
    man_list = scan_csv(
        csvfile=os.path.dirname(os.path.realpath(__file__)) + "/hostname_manuel.csv"
    )
    output = {
        "_meta": {
            "hostvars": {
                "scan_csv": {
                    "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",
            },
        },
        "csv_scan": {
            "hosts": man_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))
#  elif len(sys.argv) == 2:
#      print(sys.argv)
