#!/usr/bin/env python3
"""ArkCrossplay owner status reporter (Python 3.8+, standard library only).

Runs ON YOUR OWN server machine (Cloudflare Workers cannot send UDP queries). It asks your local ASA server for its player count with
a Steam A2S_INFO UDP query (no RCON, no admin password) and POSTs a signed status to https://arkcrossplay.com/api/status.
Shown on arkcrossplay.com only as "owner-reported" and never mixed into the Wildcard-based rankings.

Needs: your listing id and the secret that arkcrossplay.com gave you after your server was verified.
  python3 arkcrossplay_status_reporter.py --listing my-server --secret-file secret.txt --query-port 27015 --loop 120
Test without sending anything:  add --dry-run
Caveat: whether ASA answers A2S on your query port depends on your launch options/host; if the query gets no answer the script reports
the server as offline ONLY with --report-offline, otherwise it sends nothing. We have not verified A2S on every ASA setup.
"""
import argparse, hashlib, hmac, json, socket, struct, sys, time, urllib.error, urllib.request

ENDPOINT = 'https://arkcrossplay.com/api/status'
A2S = b'\xff\xff\xff\xffTSource Engine Query\x00'


def _cstr(buf, i):
    j = buf.index(b'\x00', i)
    return buf[i:j].decode('utf-8', 'replace'), j + 1


def query_a2s(host, port, timeout=3.0):
    """Return {'players','maxPlayers','map'} or None if the server did not answer."""
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(timeout)
    try:
        s.sendto(A2S, (host, port))
        data, _ = s.recvfrom(4096)
        if data[4:5] == b'\x41':                      # challenge: resend with the challenge number appended
            s.sendto(A2S + data[5:9], (host, port))
            data, _ = s.recvfrom(4096)
        if data[4:5] != b'\x49':
            return None
        i = 6                                          # skip header(4) + 'I' + protocol(1)
        _, i = _cstr(data, i)                          # server name
        game_map, i = _cstr(data, i)
        _, i = _cstr(data, i)                          # folder
        _, i = _cstr(data, i)                          # game
        i += 2                                         # app id
        players, max_players = data[i], data[i + 1]
        return {'players': int(players), 'maxPlayers': int(max_players), 'map': game_map[:60]}
    except (socket.timeout, OSError, ValueError, IndexError, struct.error):
        return None
    finally:
        s.close()


def build_request(listing, secret, status, now=None):
    """Returns (raw_body_bytes, headers). Signature = hex HMAC-SHA256(secret, f"{timestamp}.{raw_body}")."""
    ts = str(int(now if now is not None else time.time()))
    body = json.dumps({'listing': listing, **status}, separators=(',', ':')).encode()
    sig = hmac.new(secret.encode(), ts.encode() + b'.' + body, hashlib.sha256).hexdigest()
    return body, {'Content-Type': 'application/json', 'X-Timestamp': ts, 'X-Signature': sig, 'User-Agent': 'arkcrossplay-status-reporter/1'}


def post(body, headers, endpoint=ENDPOINT):
    req = urllib.request.Request(endpoint, data=body, headers=headers, method='POST')
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            return r.status
    except urllib.error.HTTPError as e:
        return e.code


def once(a, secret):
    q = query_a2s(a.host, a.query_port)
    if q is None:
        if not a.report_offline:
            print('no A2S answer; nothing sent'); return
        status = {'online': False, 'players': 0, 'maxPlayers': 0, 'map': ''}
    else:
        status = {'online': True, **q}
    body, headers = build_request(a.listing, secret, status)
    if a.dry_run:
        print('dry run, would POST', body.decode()); return
    print('status', status, '->', post(body, headers, a.endpoint))


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--listing', required=True)
    g = ap.add_mutually_exclusive_group(required=True)
    g.add_argument('--secret'); g.add_argument('--secret-file')
    ap.add_argument('--host', default='127.0.0.1'); ap.add_argument('--query-port', type=int, required=True)
    ap.add_argument('--loop', type=int, default=0, help='repeat every N seconds (min 60); 0 = once')
    ap.add_argument('--report-offline', action='store_true'); ap.add_argument('--dry-run', action='store_true')
    ap.add_argument('--endpoint', default=ENDPOINT)
    a = ap.parse_args()
    secret = a.secret or open(a.secret_file).read().strip()
    if a.loop and a.loop < 60: sys.exit('--loop must be at least 60 seconds')
    while True:
        once(a, secret)
        if not a.loop: break
        time.sleep(a.loop)


if __name__ == '__main__':
    main()
