#!/usr/bin/python3
"""Read One-KVM's configured web protocol and port without startup logs."""
from contextlib import closing
import json
from pathlib import Path
import sqlite3
import sys


def read_endpoint(data_dir):
    database = (Path(data_dir) / 'one-kvm.db').resolve()
    uri_path = str(database).replace('%', '%25').replace('?', '%3F').replace('#', '%23')
    # mode=ro never creates a missing database and observes committed WAL data.
    with closing(sqlite3.connect('file:' + uri_path + '?mode=ro', uri=True, timeout=0.25)) as connection:
        row = connection.execute("SELECT value FROM config WHERE key = 'app_config'").fetchone()
    if row is None:
        raise ValueError('application configuration is not available yet')
    web = json.loads(row[0]).get('web', {})
    secure = web.get('https_enabled', False)
    if type(secure) is not bool:
        raise ValueError('invalid HTTPS setting')
    # Match WebConfig's serde defaults when a stored field is absent.
    port = web.get('https_port', 8443) if secure else web.get('http_port', 8080)
    if type(port) is not int or not 1 <= port <= 65535:
        raise ValueError('invalid web port')
    return '{}://0.0.0.0:{}'.format('https' if secure else 'http', port)


def main():
    if len(sys.argv) != 2:
        return 2
    try:
        endpoint = read_endpoint(sys.argv[1])
    except (OSError, sqlite3.Error, ValueError, TypeError, AttributeError):
        return 1
    print(endpoint)
    return 0


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