#!/usr/bin/env python3
# @file loadDriver.py
#
# @brief Load the driver on the PC
#
# @author Manuel Castilla
# @date 16/04/2019
#
# Copyright (c) 2019 CERN (www.cern.ch).
#
# This file is part of WR Starting Kit project
# (see https://www.ohwr.org/project/wr-starting-kit).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
#(at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###########################################################################


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):
            commands = ["sudo modprobe spec","sudo modprobe htvic",
            "sudo modprobe wr-nic","sudo modprobe wr-dio"]
            for cmd in commands:
                sshCmd.exec(hostName,cmd,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")
