#!/usr/bin/env python3
"""Download a WhatsMinerTool ip.ini of our CURRENT operation: every defined
pod's real network range, straight from master_config. Save it into the WMT
folder to keep WhatsMinerTool's network map in sync with live config.

Range-based sections (one per pod), so it replaces the hand-maintained
networks list. Unlike onboard_iplist.py (single-IP onboarding targets),
this is the full site/pod map.

Query params (optional):
  check=1   mark every section enabled-for-scan (CheckState=1). default 0
            (map only; you enable the pods you want to scan in WMT).
"""
import cgi, sys

sys.path.insert(0, '/opt/ngon/apps')
from managers.auth_manager import AuthManager, generate_login_page_html
sys.path.insert(0, '/opt/ngon/apps/miners')
import gen_wmt_iplist as gen


def main():
    form = cgi.FieldStorage()
    auth = AuthManager('nmt')
    auth_required, should_exit, headers = auth.require_auth(form)

    if should_exit:
        print("Content-Type: application/json")
        if headers:
            print(headers)
        print("")
        print('{"success": false, "error": "Authentication required"}'
              if auth_required else '{"success": true}')
        return

    if auth_required:
        print("Content-Type: text/html\n")
        print(generate_login_page_html("WMT Network Map"))
        return

    check = 1 if form.getvalue('check', '0') == '1' else 0
    rows = gen.site_networks()
    body = gen.render_sections(rows, check=check)

    sys.stdout.write("Content-Type: application/octet-stream\r\n")
    sys.stdout.write('Content-Disposition: attachment; filename="ip.ini"\r\n')
    sys.stdout.write("X-Pod-Count: %d\r\n" % len(rows))
    sys.stdout.write("\r\n")
    sys.stdout.write(body)


if __name__ == "__main__":
    main()
