#!/usr/bin/python3

import sys
from itertools import takewhile

from libsvsync.rsync import validate_machine
from libsvsync.samdb import validate_samdb, init_samdb


def print_help():
    print("Usage: svsync [subcommand]")
    print("Subcommands:")
    print("  svsync help - print this message")
    print("  svsync check - call validation function and print to output it's result")

def main(args: list[str]):
    if len(args) < 1:
        print_help()
        return 2
    pass

    if len(args) > 1:
        print("Error unknown arguments: %s" % args[1:])
        print_help()
        return 2

    if args[0] == "help":
        print_help()
        return 0

    if args[0] == "check":
        try:
            lp, samdb = init_samdb()
        except:
            print("Error initializing SamDB")
            print("Try run `svsync check` from root user")
            return 2

        res1 = validate_samdb(samdb)
        res2 = validate_machine(lp)

        if not res1[0] or not res2[0]:
            for message in res1[1]:
                print(message)
            for message in res2[1]:
                print(message)
            return 1

        print("LDAP Forest:\t\t ", end='')
        if res2[0]:
            print("OK")
        else:
            print("FAILED")

        print("Machine configuration:\t ", end='')
        if res1[0]:
            print("OK")
        else:
            print("FAILED")
        print()

        print("All checked configs are valid")
        return 0

    print("Error unknown commands: %s" % args[0])
    print_help()
    return 1

if __name__ == "__main__":
    argv = list(takewhile(lambda x: x != "--", sys.argv[1:]))
    sys.exit(main(argv))
