#!/usr/bin/python3
"""
Give Grafana read access to the local InfluxDB 2 of a NaPi board.

Checks the token in /etc/grafana/napi-influx-token and creates a new one
(read access to the bucket "sensors" only) when it is missing or rejected.
The operator token is read from /root/influxdb-credentials, which
napiconfig's influx-link writes on the first start of InfluxDB.

  grafana-link [--wait SECONDS]

Idempotent. napi-grafana-link.service runs it at every boot before Grafana,
so the token is created on the device, never in an image.
"""

import argparse
import grp
import json
import os
import shlex
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

URL = 'http://127.0.0.1:8086'
ORG = 'napi'
BUCKET = 'sensors'
CREDENTIALS = Path('/root/influxdb-credentials')
TOKEN_FILE = Path('/etc/grafana/napi-influx-token')
DESCRIPTION = 'grafana, read-only (napi-grafana)'


def log(msg):
    print(f'grafana-link: {msg}', flush=True)


def api(method, path, token=None, body=None, params=None):
    url = URL + path
    if params:
        url += '?' + urllib.parse.urlencode(params)
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, method=method)
    req.add_header('Content-Type', 'application/json')
    if token:
        req.add_header('Authorization', f'Token {token}')
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            status, raw = resp.status, resp.read()
    except urllib.error.HTTPError as e:
        status, raw = e.code, e.read()
    try:
        return status, json.loads(raw) if raw else None
    except ValueError:
        return status, None


def wait_ready(timeout):
    deadline = time.monotonic() + timeout
    while True:
        try:
            status, body = api('GET', '/health')
            if status == 200 and body and body.get('status') == 'pass':
                return True
        except OSError:
            pass
        if time.monotonic() >= deadline:
            return False
        time.sleep(2)


def operator_token():
    if not CREDENTIALS.exists():
        return None
    for line in CREDENTIALS.read_text().splitlines():
        key, sep, value = line.partition('=')
        if sep and key.strip() == 'INFLUXDB_TOKEN':
            parts = shlex.split(value)
            return parts[0] if parts else None
    return None


def token_works(token):
    status, body = api('GET', '/api/v2/buckets', token=token, params={'name': BUCKET})
    return status == 200 and bool(body and body.get('buckets'))


def write_token(token):
    try:
        gid = grp.getgrnam('grafana').gr_gid
    except KeyError:
        gid = 0
    TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
    tmp = TOKEN_FILE.with_name(TOKEN_FILE.name + '.tmp')
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o640)
    with os.fdopen(fd, 'w') as f:
        f.write(token)
    os.chown(tmp, 0, gid)
    os.chmod(tmp, 0o640)
    tmp.replace(TOKEN_FILE)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--wait', type=int, default=0, help='seconds to wait for InfluxDB')
    args = ap.parse_args()

    # Grafana refuses to start when the file of $__file{} is missing.
    if not TOKEN_FILE.exists():
        write_token('')
    if not wait_ready(args.wait):
        log('InfluxDB is not answering on 127.0.0.1:8086, nothing done')
        return 0
    if TOKEN_FILE.exists():
        current = TOKEN_FILE.read_text().strip()
        if current and token_works(current):
            write_token(current)  # keep owner and mode right after a reinstall
            log('token is valid')
            return 0
    admin = operator_token()
    if not admin:
        log(f'no operator token in {CREDENTIALS} (is napiconfig installed?), nothing done')
        return 0
    status, body = api('GET', '/api/v2/buckets', token=admin, params={'name': BUCKET})
    if status != 200 or not body or not body.get('buckets'):
        log(f'bucket "{BUCKET}" not found ({status}), nothing done')
        return 0
    bucket = body['buckets'][0]
    status, body = api('POST', '/api/v2/authorizations', token=admin, body={
        'orgID': bucket['orgID'],
        'description': DESCRIPTION,
        'permissions': [{
            'action': 'read',
            'resource': {'type': 'buckets', 'id': bucket['id'], 'orgID': bucket['orgID']},
        }],
    })
    if status != 201 or not body or not body.get('token'):
        log(f'cannot create a token: {status}')
        return 1
    write_token(body['token'])
    log(f'new read token for Grafana, bucket "{BUCKET}"')
    return 0


if __name__ == '__main__':
    sys.exit(main())
