#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import re
import socket
import struct
import subprocess

CONFIG = "/var/efw/routing/kernel/config"
STATE_DIR = "/var/run/efw/routing"
STATE = os.path.join(STATE_DIR, "kernel.routes")


def run(cmd, quiet=True):
    try:
        if quiet:
            subprocess.call(cmd, stdout=open(os.devnull, "w"), stderr=open(os.devnull, "w"))
        else:
            subprocess.call(cmd)
    except Exception:
        pass


def ip_to_long(ip):
    try:
        return struct.unpack("!I", socket.inet_aton(ip))[0]
    except Exception:
        return None


def in_cidr(ip, cidr):
    try:
        net, mask = cidr.split("/")
        mask = int(mask)
    except Exception:
        return False
    ipl = ip_to_long(ip)
    netl = ip_to_long(net)
    if ipl is None or netl is None:
        return False
    if mask == 0:
        return True
    bits = (0xFFFFFFFF << (32 - mask)) & 0xFFFFFFFF
    return (ipl & bits) == (netl & bits)


def connected_prefixes():
    prefixes = []
    try:
        out = subprocess.check_output(["ip", "-4", "addr", "show"], stderr=open(os.devnull, "w"))
    except Exception:
        out = ""
    for m in re.finditer(r"inet\s+(\d+\.\d+\.\d+\.\d+/\d+)", out):
        prefixes.append(m.group(1))
    try:
        out = subprocess.check_output(["ip", "-4", "route", "show", "scope", "link"], stderr=open(os.devnull, "w"))
    except Exception:
        out = ""
    for line in out.splitlines():
        m = re.match(r"^(\d+\.\d+\.\d+\.\d+/\d+)", line)
        if m:
            prefixes.append(m.group(1))
        m = re.match(r"^(\d+\.\d+\.\d+\.\d+)\s+dev\s", line)
        if m:
            prefixes.append(m.group(1) + "/32")
    # dedup
    seen = set()
    uniq = []
    for p in prefixes:
        if p in seen:
            continue
        seen.add(p)
        uniq.append(p)
    return uniq


def gateway_reachable(gw):
    for p in connected_prefixes():
        if in_cidr(gw, p):
            return True
    return False


def valid_dest(dest):
    if dest.lower() == "default":
        return True
    if "/" in dest:
        ip, mask = dest.split("/", 1)
        if not re.match(r"^\d{1,3}(\.\d{1,3}){3}$", ip):
            return False
        try:
            m = int(mask)
        except Exception:
            return False
        if m < 0 or m > 32:
            return False
        if ip_to_long(ip) is None:
            return False
        first = int(ip.split(".")[0])
        if first >= 224:
            return False
        return True
    if not re.match(r"^\d{1,3}(\.\d{1,3}){3}$", dest):
        return False
    if ip_to_long(dest) is None:
        return False
    first = int(dest.split(".")[0])
    if first >= 224:
        return False
    return True


def valid_gw(gw):
    if not re.match(r"^\d{1,3}(\.\d{1,3}){3}$", gw):
        return False
    if ip_to_long(gw) is None:
        return False
    return gateway_reachable(gw)


def main():
    try:
        os.makedirs(STATE_DIR)
    except OSError:
        pass

    # remove previously managed routes
    if os.path.isfile(STATE):
        try:
            with open(STATE, "r") as f:
                for line in f:
                    dest = line.strip()
                    if not dest:
                        continue
                    run(["ip", "route", "del", dest])
        except Exception:
            pass

    # reset state
    try:
        with open(STATE, "w") as f:
            pass
    except Exception:
        pass

    if not os.path.isfile(CONFIG):
        run(["ip", "route", "flush", "cache"])
        return

    managed = []
    try:
        with open(CONFIG, "r") as f:
            for raw in f:
                line = raw.strip()
                if not line:
                    continue
                parts = line.split(",")
                # enabled,destination,gateway,metric,remark
                if len(parts) < 3:
                    continue
                enabled = parts[0].strip()
                dest = parts[1].strip()
                gw = parts[2].strip()
                metric = parts[3].strip() if len(parts) > 3 else ""

                if enabled != "on":
                    continue
                if not dest or not gw:
                    continue

                # validation
                if not valid_dest(dest):
                    continue
                if not valid_gw(gw):
                    continue
                if metric and (not metric.isdigit() or int(metric) > 65535):
                    continue

                cmd = ["ip", "route", "replace", dest, "via", gw]
                if metric:
                    cmd += ["metric", metric]
                run(cmd)
                managed.append(dest)
    except Exception:
        pass

    try:
        with open(STATE, "w") as f:
            for dest in managed:
                f.write(dest + "\n")
    except Exception:
        pass

    run(["ip", "route", "flush", "cache"])


if __name__ == "__main__":
    main()
