#!/usr/bin/env python3
"""Complete fresh MAIN bootstrap when install.py stalls (schema + config)."""
import base64
import json
import os
import random
import re
import socket
import string
import subprocess
import sys
from itertools import cycle

XTREAM_BASE = "/home/xtreamcodes/iptv_xtream_codes"
DB_PORT = 7999
XOR_KEY = "5709650b0d7806074842c6de575025b1"
VLAN_IP = os.environ.get("MAIN_VLAN", "")


def generate(n=19):
    return "".join(random.choice(string.ascii_letters + string.digits) for _ in range(n))


def mysql_sql(sql):
    p = subprocess.run(
        ["mysql", "-u", "root"],
        input=sql,
        text=True,
        capture_output=True,
    )
    if p.returncode != 0:
        print(p.stderr.strip() or p.stdout.strip(), file=sys.stderr)
    return p.returncode == 0


def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("8.8.8.8", 80))
        return s.getsockname()[0]
    finally:
        s.close()


def detect_vlan():
    if VLAN_IP:
        return VLAN_IP
    try:
        out = subprocess.check_output(["ip", "-4", "addr", "show"], text=True)
        for line in out.splitlines():
            if "17.17.17." in line:
                return line.strip().split()[1].split("/")[0]
    except Exception:
        pass
    return ""


def get_network_interface():
    try:
        out = subprocess.check_output(["ip", "route", "get", "8.8.8.8"], text=True)
        m = re.search(r"\bdev\s+(\S+)", out)
        return m.group(1) if m else "eth0"
    except Exception:
        return "eth0"


def get_version():
    try:
        out = subprocess.check_output(["lsb_release", "-d"], text=True)
        return out.split(":")[-1].strip()
    except Exception:
        return ""


def main():
    db_schema = os.environ.get("DB_SCHEMA", "/tmp/database.sql")
    settings_seed = os.environ.get("SETTINGS_SEED", "/tmp/settings_seed.sql")
    vlan = detect_vlan()
    main_ip = get_ip()
    db_pass = generate()
    username = "user_iptvpro"

    if not os.path.isfile(db_schema):
        raise SystemExit("missing %s — mirror must include database.sql" % db_schema)

    subprocess.run(
        ["mysql", "-u", "root", "-e", "DROP DATABASE IF EXISTS xtream_iptvpro; CREATE DATABASE xtream_iptvpro;"],
        check=False,
    )
    with open(db_schema) as f:
        p = subprocess.run(["mysql", "-u", "root", "xtream_iptvpro"], stdin=f, capture_output=True)
    if p.returncode != 0:
        raise SystemExit("database import failed: " + (p.stderr.decode() or p.stdout.decode()))

    if os.path.isfile(settings_seed):
        with open(settings_seed) as f:
            subprocess.run(["mysql", "-u", "root", "xtream_iptvpro"], stdin=f, check=False)

    sqls = [
        "USE xtream_iptvpro; UPDATE settings SET live_streaming_pass='%s', unique_id='%s', crypt_load_balancing='%s', get_real_ip_client='';"
        % (generate(20), generate(10), generate(20)),
        "USE xtream_iptvpro; REPLACE INTO streaming_servers "
        "(id, server_name, domain_name, server_ip, vpn_ip, ssh_password, ssh_port, diff_time_main, "
        "http_broadcast_port, total_clients, system_os, network_interface, latency, status, enable_geoip, "
        "geoip_countries, last_check_ago, can_delete, server_hardware, total_services, persistent_connections, "
        "rtmp_port, geoip_type, isp_names, isp_type, enable_isp, boost_fpm, http_ports_add, "
        "network_guaranteed_speed, https_broadcast_port, https_ports_add, whitelist_ips, watchdog_data, "
        "timeshift_only) VALUES (1, 'Main Server', '', '%s', '%s', NULL, NULL, 0, 80, 1000, '%s', '%s', "
        "0, 1, 0, '', 0, 0, '{}', 3, 0, 2095, 'low_priority', '', 'low_priority', 0, 1, '', 1000, 443, '', "
        "'[\"127.0.0.1\",\"\"]', '{}', 0);"
        % (main_ip, vlan, get_version(), get_network_interface()),
        "USE xtream_iptvpro; REPLACE INTO reg_users "
        "(id, username, password, email, member_group_id, verified, status) VALUES "
        "(1, 'admin', "
        "'$6$rounds=20000$xtreamcodes$XThC5OwfuS0YwS4ahiifzF14vkGbGsFF1w7ETL4sRRC5sOrAWCjWvQJDromZUQoQuwbAXAFdX3h3Cp3vqulpS0', "
        "'admin@website.com', 1, 1, 1);",
        "CREATE USER IF NOT EXISTS '%s'@'%%' IDENTIFIED BY '%s'; "
        "GRANT ALL PRIVILEGES ON xtream_iptvpro.* TO '%s'@'%%' WITH GRANT OPTION; "
        "GRANT SELECT, LOCK TABLES ON *.* TO '%s'@'%%'; FLUSH PRIVILEGES;"
        % (username, db_pass, username, username),
        "USE xtream_iptvpro; CREATE TABLE IF NOT EXISTS dashboard_statistics "
        "(id int(11) NOT NULL AUTO_INCREMENT, type varchar(16) NOT NULL DEFAULT '', "
        "time int(16) NOT NULL DEFAULT '0', count int(16) NOT NULL DEFAULT '0', "
        "PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1; "
        "INSERT IGNORE INTO dashboard_statistics (type, time, count) VALUES "
        "('conns', UNIX_TIMESTAMP(), 0),('users', UNIX_TIMESTAMP(), 0);",
    ]
    for s in sqls:
        if not mysql_sql(s):
            raise SystemExit("SQL failed: " + s[:100])

    plain = json.dumps(
        {
            "host": "127.0.0.1",
            "db_user": username,
            "db_pass": db_pass,
            "db_name": "xtream_iptvpro",
            "server_id": 1,
            "db_port": DB_PORT,
        }
    )
    key = cycle(XOR_KEY)
    xored = "".join(chr(ord(c) ^ ord(k)) for c, k in zip(plain, key))
    encoded = base64.b64encode(xored.encode("latin-1")).decode("ascii")
    with open(XTREAM_BASE + "/config", "w") as f:
        f.write(encoded)
    os.chmod(XTREAM_BASE + "/config", 0o700)
    print("DB_PASS=" + db_pass)
    print("MAIN_IP=" + main_ip)
    print("VLAN_IP=" + vlan)


if __name__ == "__main__":
    main()
