"""
Usage: webtech-admin [options] init
       webtech-admin [options] host-sign <publickey> <principals>
       webtech-admin [options] serve
       webtech-admin -h | --help

Commands:
    init                    Initialize the webtech-admin db, ssh-ca keys
    host-sign               Sign a specific host public key with the given principals
    serve                   Start the webtech-admin frontend server
       
Options:
    -h --help               Show this help screen.
    -c FILE, --config FILE  Specify configuration file [default: webtech-admin.toml]
"""

import docopt

from .ssh_ca import SSHCA
from .crypto import SSHCertificateType, load_pub_key
from .config import Config
from .server import Server
from .database import Database


def main():
    opts = docopt.docopt(__doc__)

    cfg = Config.from_file(opts["--config"])

    ssh_ca = SSHCA(cfg)

    if opts["init"]:
        ssh_ca.do_init()
        # auto-inits database
        db = Database(cfg.lookup("general.db_path"))
    elif opts["host-sign"]:
        with open(opts["<publickey>"], "rb") as f:
            public_key = f.read()

        cert = ssh_ca.do_sign(
            public_key, SSHCertificateType.HOST, principals=opts["<principals>"]
        )

        print(cert.public_bytes())
    elif opts["serve"]:
        ssh_ca.do_init()
        server = Server(cfg, ssh_ca)
        server.run()


main()
