#!/usr/bin/env python3
# summary: Make a fleet install stick from Mission Control.
"""Usage: starchaser fleet stick check | make | enroll TOKEN | join | revoke TOKEN
make reads the selected USB drive, Wi-Fi and name pattern as JSON on stdin.
join consumes the installer's private enrollment profile at first sign-in.
revoke immediately ends enrollment from that stick; already joined computers stay joined.
"""
import json
import os
import re
import sys
from pathlib import Path
import starchaser_fleet_stick as stick


def main():
    args = sys.argv[1:]
    if args in (['--help'], ['-h'], ['help']):
        print(__doc__); return 0
    try:
        if args == ['list']:
            result = dict(ok=True, sticks=[dict(token=p.parent.name, **json.loads(p.read_text())) for p in stick.STATE.glob('*/grant.json')])
        elif args == ['check']:
            result = stick.check(json.loads(sys.stdin.read(32769)))
        elif args == ['make']:
            result = stick.make(json.loads(sys.stdin.read(32769)))
        elif len(args) == 2 and args[0] == 'enroll':
            result = stick.enroll(args[1])
        elif len(args) == 2 and args[0] == 'revoke' and re.fullmatch(r'[a-f0-9]{32}', args[1]):
            stick.module('link').fleet().authkeys('remove', 'starchaser-install:' + args[1])
            (stick.STATE / args[1] / 'grant.json').unlink(missing_ok=True)
            result = dict(ok=True)
        elif args == ['join']:
            config = Path.home() / '.local/state/starchaser/fleet-install.json'
            if not config.is_file():
                return 0
            result = stick.join(json.loads(config.read_text()))
            if result.get('ok'):
                config.unlink()
        else:
            print(__doc__, file=sys.stderr); return 2
    except (ValueError, OSError, KeyError, TypeError) as error:
        result = dict(ok=False, error=str(error))
    print(json.dumps(result))
    return 0 if result.get('ok') else 1


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