#!/usr/bin/env python3
# @file loadDriver.py
#
# @brief Load the driver on the PC
#
# @author Manuel Castilla
# @date 16/04/2019
#
###########################################################################

from ssh import SshCmd,SshCmdException
import sys
import getpass
error = -1

def loadDriver(hostName,userName,password):
    """
    This function load the driver on the PC

    Args:
        hostName: ip remote host
        username: user name
        password: password

    Return:
        True if the driver was loaded correctly, False otherwise
    """
    ret = 0
    try:
        sshCmd = SshCmd()
        command = "ifconfig | grep wr | wc -l"
        value = sshCmd.exec(hostName,command,userName,password)
        if (int(value) == 0):
            command = "sudo modprobe -r spec"
            sshCmd.exec(hostName,command,userName,password)
            command = "sudo modprobe -r wr-nic"
            sshCmd.exec(hostName,command,userName,password)
            command = "sudo modprobe spec"
            sshCmd.exec(hostName,command,userName,password)
            command = "sudo insmod /lib/modules/$(uname -r)/extra/wr-nic.ko wrc=1" #esto es temporal
            sshCmd.exec(hostName,command,userName,password)
            command = "sudo modprobe wr-nic"
            sshCmd.exec(hostName,command,userName,password)
            command = "ifconfig | grep wr | wc -l"
            value = sshCmd.exec(hostName,command,userName,password)
            if (int(value) == 0):
                ret = error
        else:
            print("The driver was previously loaded")
    except SshCmdException as e:
        sshCmd.printSshErrorCommand(e.strError)
        ret = error
    return ret

#--------------------------------------------------#
#--------------------------------------------------#
# MAIN
#--------------------------------------------------#
#--------------------------------------------------#
if len(sys.argv) < 2:
    print("usage: app hostaname")
    sys.exit(1)

hostName = sys.argv[1]
userName = input("Please enter username: ")
#password = getpass("Please enter password: ")
password = getpass.getpass()

if (loadDriver(hostName,userName,password) == 0):
    print("Load driver: ok")
else:
    print("Load driver: error")
