#!/usr/bin/python

# All Rights reserved.
#
# This software is subject to the Cumulus Networks End User License Agreement available
# at the following locations:.
#
# Internet: https://cumulusnetworks.com/downloads/eula/latest/view/
#
# Cumulus Linux systems: /usr/share/cumulus/EULA.txt

"""
Usage:
    cl-chassis [<ipv6>|all] license-install path <text>
    cl-chassis [<ipv6>|all] reboot
    cl-chassis [<ipv6>|all] nos-install path <text>
    cl-chassis [<ipv6>|all] daemon restart <text>
    cl-chassis [<ipv6>|all] cl-support

Options:
    <ipv6> : Link local IPv6 address of an endpoint
    all : All endpoints within a chassis
    license-install : Install license for Cumulus Linux
    path : Path on the local system or a URL
    reboot : Reboot endpoint in a CLOS
    nos-install : Install a new Cumulus Linux binary image (Destructive!!!! Please backup important files)
    daemon: Cumulus Linux Daemon related operations
    restart : Systemd restart of a service
"""

import sys
import httplib
import socket
import cumulus.chassis
from network_docopt import NetworkDocopt, get_network_docopt_info
import subprocess
import pwd
import os


class ChassisCli(NetworkDocopt):

    def run(self):
        NetworkDocopt.run(self)
        if len(sys.argv) == 1:
            return
        net_cmd = ['net', 'run', ]

        for index in xrange(1, len(sys.argv)):
            net_cmd.append(sys.argv[index])
        try:
            output = subprocess.check_output(net_cmd)
        except subprocess.CalledProcessError as e:
            print e.output
            return False

        print output

        if 'FAIL' in output:
            return False

        return True

if __name__ == "__main__":
    # Check if we are running on chassis, else
    # exit.
    try:
        chassis = cumulus.chassis.probe()
    except (ImportError, RuntimeError, AssertionError) as e:
        print "You're not running on a chassis. Type: %s" % (e,)
        exit(0)
    # Check if script is being run as root
    user = pwd.getpwuid(os.getuid())[0]
    if user != 'root':
        print "User %s does not have permission to run this script" % user
        exit(1)
    (print_options, ended_with_space, sys.argv) = get_network_docopt_info(sys.argv)
    cli = ChassisCli(__doc__)
    if print_options:
        cli.print_options(ended_with_space)
    else:
        if cli.run():
            exit(0)
        else:
            exit(1)


