#!/usr/bin/env python3
import sys
import urllib.request
import json
from collections import Counter
import subprocess


def ban_ip(ip, country):
    # CSAK akkor tiltunk, ha NEM magyar, nem ismeretlen és érvényes IP
    if country != "HU" and country != "ISMERETLEN" and ip != "ismeretlen":
        try:
            # 1. Ellenőrzés: Szerepel-e már a tűzfal szabályok között?
            # A 'grep -q' csendben fut, csak visszatérési értéket ad (0 ha van találat)
            check_cmd = f"sudo ufw status | grep -w '{ip}'"
            already_exists = subprocess.call(check_cmd, shell=True, stdout=subprocess.DEVNULL) == 0
            
            if already_exists:
                return "MÁR VOLT SZABÁLY"
            
            # 2. Ha nincs még benne, felvesszük
            add_cmd = ["sudo", "ufw", "deny", "from", ip]
            output = subprocess.check_output(add_cmd).decode("utf-8").strip()
            return f"ÚJ TILTÁS ({output})"
        except Exception as e:
            return f"HIBA: {e}"
    return "NEM TILTVA (Magyar/Ismeretlen)"
    

def get_geo(ip):
    if ip == "ismeretlen" or not ip:
        return "Ismeretlen"
    try:
        # A whois parancs futtatása, csak az országkódot keressük (grep -i country)
        cmd = f"whois {ip} | grep -iE '^country:' | head -1"
        result = subprocess.check_output(cmd, shell=True).decode("utf-8").strip()
        
        # Példa kimenet: "country:        HU"
        if ":" in result:
            country_code = result.split(":")[1].strip().upper()
            return country_code
    except:
        pass
    return "Nincs adat"


def get_geo_4(ip):
    if ip == "ismeretlen" or not ip:
        return "Ismeretlen"
    try:
        # Meghívjuk a helyi geoip parancsot
        result = subprocess.check_output(["geoiplookup", ip]).decode("utf-8")
        # Példa kimenet: "GeoIP Country Edition: HU, Hungary"
        if "Country Edition:" in result:
            country = result.split(":").strip()
            return country
    except:
        pass
    return "Nincs adat"



def get_geo_IPAPICOM(ip):
    if ip == "ismeretlen" or not ip:
        return "Ismeretlen"
    try:
        # Ez a végpont (ip-api.com) nem blokkolja a Python-t
        url = f"https://ip-api.com/{ip}?fields=status,message,country,city"
        with urllib.request.urlopen(url, timeout=5) as response:
            data = json.loads(response.read().decode())
            if data.get('status') == 'success':
                # Itt a mezőnevek: 'country' és 'city'
                return f"{data['country']} ({data['city']})"
            else:
                return f"Hiba: {data.get('message', 'ismeretlen')}"
    except Exception as e:
        return "Lekérdezési hiba"



def get_geo_IPAPICO_XXX(ip):
    if ip == "ismeretlen":
        return "Ismeretlen"
    try:
        # URL javítva: /json/ hozzáadva
        url = f"https://ip-api.co/{ip}/json/"
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req, timeout=5) as response:
            data = json.loads(response.read().decode())
            # A JSON válaszod alapján ezeket a mezőket használjuk
            if 'country_name' in data:
                return f"{data['country_name']} ({data.get('city', 'N/A')})"
    except:
        pass
    return "Ismeretlen"

def mail_summary(conn_type, domain_filter, status_filter):
    log_path = '/var/log/mail.log'
    stats = Counter()
    last_ip = {}
    
    show_all_domains = domain_filter.lower() in ['.', '', 'all', 'any']

    try:
        with open(log_path, 'r', errors='ignore') as f:
            for line in f:
                if conn_type.lower() in line.lower() and status_filter.upper() in line.upper():
                    
                    if "user=" in line:
                        parts = line.split("user=")
                        user = parts[1].split(",")[0].strip()
                        
                        # Csak akkor foglalkozunk vele, ha a domain egyezik
                        if show_all_domains or domain_filter.lower() in user.lower():
                            ip = "ismeretlen"
                            if "ip=[" in line:
                                ip_part = line.split("ip=[")[1].split("]")[0]
                                ip = ip_part.replace("::ffff:", "")
                            
                            stats[user] += 1
                            last_ip[user] = ip

        if not stats:
            print(f"\nNincs találat! (Szűrők: {conn_type}, {domain_filter}, {status_filter})")
            return

        # Fejléc (szélesebb az új oszlop miatt)
        print(f"\n{'Típus':<7} | {'Fiók név':<35} | {'IP (utolsó)':<15} | {'GEO IP':<10} | {'Találat'}")
        print("-" * 105)
        
        summary_info = []

        for user, count in stats.most_common():
            country = get_geo(last_ip[user])
            print(f"{conn_type.upper():<7} | {user:<35} | {last_ip[user]:<15} | {country:<10} | {count} db")
            
            # Tiltás kezelése
            status = ban_ip(last_ip[user], country)
            
            if "ÚJ TILTÁS" in status:
                summary_info.append(f"[+] ÚJ SZABÁLY: {last_ip[user]} ({country}) hozzáadva.")
            elif "MÁR VOLT SZABÁLY" in status:
                summary_info.append(f"[*] MÁR TILTVA: {last_ip[user]} ({country}) már korábban szerepelt.")

        # Összegzés kiírása
        if summary_info:
            print("\n--- TŰZFAL ÖSSZEGZÉS ---")
            for line in summary_info:
                print(line)                

    except Exception as e:
        print(f"Hiba: {e}")

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Használat: sudo python3 mail_summary.py pop3d all FAILED")
        sys.exit(1)

    c_type = sys.argv[1]
    d_filt = sys.argv[2]
    s_filt = sys.argv[3]

    mail_summary(c_type, d_filt, s_filt)
