#!/usr/bin/env python3
# +------------------------------------------------------------+
# |                                                            |
# |             | |             | |            | |             |
# |          ___| |__   ___  ___| | ___ __ ___ | | __          |
# |         / __| '_ \ / _ \/ __| |/ / '_ ` _ \| |/ /          |
# |        | (__| | | |  __/ (__|   <| | | | | |   <           |
# |         \___|_| |_|\___|\___|_|\_\_| |_| |_|_|\_\          |
# |                                   custom code by SVA       |
# |                                                            |
# +------------------------------------------------------------+
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   Copyright (C) 2024  SVA System Vertrieb Alexander GmbH
#                       by michael.hoess@sva.de


from typing import Mapping, Optional

import json
import requests
import sys


"""
http://192.168.100.1/ONT/client/html/content/overview/status.html?lang=de'   
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'   
-H 'Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'   
-H 'Cache-Control: no-cache'   -H 'Connection: keep-alive'   -H 'Cookie: lang=de'   
-H 'Pragma: no-cache'   -H 'Referer: http://192.168.100.1/ONT/client/html/content/overview/status.html?lang=de'   
-H 'Upgrade-Insecure-Requests: 1'   
-H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
"""


def fetch_data(host: str) -> Optional[Mapping]:

    # url = f"http://{host}/ONT/client/html/content/overview/status.html?lang=de"
    # url_overview = f"http://{host}/ONT/client/html/content/overview/index.html?lang=de"

    url_status = f"http://{host}/ONT/client/data/Status.json"
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Language": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7",
    }

    r = requests.get(url_status, headers=headers)
    if r.status_code == 200:
        return r.json()
    else:
        sys.stderr.write(f"Request failed: {r.status_code} {r.text}\n")
        return None

    return None


if len(sys.argv) != 2:
    sys.stderr.write("Invalid args:\nInvoke with PROGNAME [host/ip]\n")
    sys.exit(1)

host = sys.argv[1]
data = fetch_data(host)
if data is None:
    sys.exit(2)

print("<<<tkom_glasmodem2:sep(0)>>>")
print(json.dumps(data))
