#!/usr/bin/python
# _*_ coding: utf-8 _*_


#import modules
from pexpect import *
import MySQLdb as mdb
import pexpect, pxssh
import sys, os, getpass, subprocess, shutil


#define variables
con = None


#functions
def doScp(user,password, host, path, files):
    fNames = ' '.join(files)
    #print fNames
    child = pexpect.spawn('scp %s %s@%s:%s' % (fNames, user, host,path))
    #print 'scp %s %s@%s:%s' % (fNames, user, host,path)
    i = child.expect(['assword:', r"yes/no"], timeout=30)
    if i == 0:
        child.sendline(password)
    elif i == 1:
        child.sendline("yes")
        child.expect("assword:", timeout=30)
        child.sendline(password)
    data = child.read()
    #print data
    child.close()


try:
    print "**********************************************************"
    print "      Installing / updating Atlantis ILIO with SNMP       "
    print "**********************************************************"


    #--------- ILIO Center ----------
    #determine if current host needs to be updated as well
    updateThisHost = raw_input('\nDo you want to update this host (%s)? (y/n): ' % os.uname()[1])
    if updateThisHost == 'y':
         output = subprocess.check_output("ps aux", shell=True)
         if "/dev/null" in output:
             print "  [1/4] copy packages (skipped, already installed)"
             print "  [2/4] install packages (skipped, already installed)"

         else: 
             print "  [1/4] copy packages"
             shutil.copy(os.path.abspath(".") + "/DEB/libperl5.10_5.10.1-17ubuntu4.1_amd64.deb", "/var/cache/apt/archives")
             shutil.copy(os.path.abspath(".") + "/DEB/libsensors4_3.3.2-2_amd64.deb", "/var/cache/apt/archives")
             shutil.copy(os.path.abspath(".") + "/DEB/libsnmp-base_5.4.3~dfsg-2_all.deb", "/var/cache/apt/archives")
             shutil.copy(os.path.abspath(".") + "/DEB/libsnmp15_5.4.3~dfsg-2_amd64.deb", "/var/cache/apt/archives")
             shutil.copy(os.path.abspath(".") + "/DEB/snmp_5.4.3~dfsg-2_amd64.deb", "/var/cache/apt/archives")
             shutil.copy(os.path.abspath(".") + "/DEB/snmpd_5.4.3~dfsg-2_amd64.deb", "/var/cache/apt/archives")


             print "  [2/4] install packages"
             output = subprocess.check_output("dpkg -i /var/cache/apt/archives/libperl5.10_5.10.1-17ubuntu4.1_amd64.deb", shell=True)
             output = subprocess.check_output("dpkg -i /var/cache/apt/archives/libsensors4_3.3.2-2_amd64.deb", shell=True)
             output = subprocess.check_output("dpkg -i /var/cache/apt/archives/libsnmp-base_5.4.3~dfsg-2_all.deb", shell=True)
             output = subprocess.check_output("dpkg -i /var/cache/apt/archives/libsnmp15_5.4.3~dfsg-2_amd64.deb", shell=True)
             output = subprocess.check_output("dpkg -i /var/cache/apt/archives/snmp_5.4.3~dfsg-2_amd64.deb", shell=True)
             output = subprocess.check_output("dpkg -i /var/cache/apt/archives/snmpd_5.4.3~dfsg-2_amd64.deb", shell=True)
 
         print "  [3/4] copy configuration and MIB files"
         if not os.path.exists("/usr/share/snmp/mibs/"):
             os.makedirs("/usr/share/snmp/mibs/")
         shutil.copy(os.path.abspath(".") + "/snmpd.conf", "/etc/snmp/")
         shutil.copy(os.path.abspath(".") + "/snmpd", "/etc/default/")
         shutil.copy(os.path.abspath(".") + "/MIB/ATLANTIS-MIB.txt", "/usr/share/snmp/mibs/")
         shutil.copy(os.path.abspath(".") + "/MIB/SNMPv2-MIB.txt", "/usr/share/snmp/mibs/")
         shutil.copy(os.path.abspath(".") + "/MIB/SNMPv2-SMI.txt", "/usr/share/snmp/mibs/")
         shutil.copy(os.path.abspath(".") + "/MIB/SNMPv2-TC.txt", "/usr/share/snmp/mibs/")
         shutil.copy(os.path.abspath(".") + "/MIB/UCD-SNMP-MIB.txt", "/usr/share/snmp/mibs/")

         print "  [4/4] restart services"
         output = subprocess.check_output("/etc/init.d/snmpd restart", shell=True)

         #determine if snmp is installed successfully
         output = subprocess.check_output("ps aux", shell=True)
         if "snmpd.pid" in output:
             print "  SUCCESS\n"
         else: 
             print "  FAILED (snmpd is NOT running)\n"
    #--------------------------------


    #--------- ILIO Appliances ----------
    #setup database connection
    con = mdb.connect('localhost', 'root', 'admin', 'ibert')
    cur = con.cursor()
    cur.execute("select ip_address,id,name from entities order by name")
    numrows = int(cur.rowcount)
    
    #determine if the ILIOs needs to be updated    
    updateILIOs = raw_input('Do you want to update the ILIO appliances (%s found)? (y/n): ' % numrows)
    if updateILIOs == 'y':

       #determine ILIO credentials
       username = 'poweruser'
       password=getpass.getpass("Enter the master password for all ILIOs (leave blank if none): ")
       if not password:
          useMasterPassword = 'n'
       else:
          useMasterPassword = 'y'
    
       #iterate through ILIO appliances
       for i in range(numrows):
           row = cur.fetchone()
           print "\nHost {host} [{ip}] is updated ({row} of {rows})".format(host=row[2], ip=row[0], row=i+1, rows=numrows)
           s = pxssh.pxssh()
           s.force_password = True
        
           #determine ILIO password (if necessary)
           if useMasterPassword == 'n':
               password=getpass.getpass("  Enter the password for ILIO %s: " % row[2])
        
           #try to login via SSH
           print "  [1/5] connect to remote host"
           if not s.login (row[0] , username, password):
               print "  ! Failed to get SSH connection to ILIO !"
               print ""
           else:
               #determine if snmp daemon is already running
               s.sendline ('ps aux|grep -v grep|grep snmpd')| s.prompt()
               if "/dev/null" in s.before:
                   print "  [2/5] upload packages (skipped, already installed)"
                   print "  [3/5] install packages (skipped, already installed)"
            
               else:
                   print "  [2/5] upload packages"
                   doScp(username, password, row[0], '/var/cache/apt/archives/',[os.path.abspath(".")+"/DEB/libsnmp15_5.4.3~dfsg-2.7_amd64.deb", os.path.abspath(".")+"/DEB/libsnmp-base_5.4.3~dfsg-2.7_all.deb", os.path.abspath(".")+"/DEB/snmp_5.4.3~dfsg-2.7_amd64.deb", os.path.abspath(".")+"/DEB/snmpd_5.4.3~dfsg-2.7_amd64.deb"])
                
                   print "  [3/5] install packages"
                   s.sendline ('dpkg -i /var/cache/apt/archives/libsnmp-base_5.4.3~dfsg-2.7_all.deb') | s.prompt() 
                   s.sendline ('dpkg -i /var/cache/apt/archives/libsnmp15_5.4.3~dfsg-2.7_amd64.deb')  | s.prompt()
                   s.sendline ('dpkg -i /var/cache/apt/archives/snmp_5.4.3~dfsg-2.7_amd64.deb')       | s.prompt()
                   s.sendline ('dpkg -i /var/cache/apt/archives/snmpd_5.4.3~dfsg-2.7_amd64.deb')      | s.prompt() 

               print "  [4/5] copy configuration and MIB files"
               doScp(username, password, row[0], '/etc/default/',[os.path.abspath(".")+"/snmpd"])
               doScp(username, password, row[0], '/etc/snmp/',[os.path.abspath(".")+"/snmpd.conf"])
               doScp(username, password, row[0], '/usr/share/snmp/mibs/',[os.path.abspath(".")+"/MIB/ATLANTIS-MIB.txt"])
               doScp(username, password, row[0], '/usr/share/snmp/mibs/',[os.path.abspath(".")+"/MIB/SNMPv2-MIB.txt"])
               doScp(username, password, row[0], '/usr/share/snmp/mibs/',[os.path.abspath(".")+"/MIB/SNMPv2-SMI.txt"])
               doScp(username, password, row[0], '/usr/share/snmp/mibs/',[os.path.abspath(".")+"/MIB/SNMPv2-TC.txt"])
               doScp(username, password, row[0], '/usr/share/snmp/mibs/',[os.path.abspath(".")+"/MIB/UCD-SNMP-MIB.txt"])

               print "  [5/5] restart services"
               s.sendline ('/etc/init.d/snmpd restart') | s.prompt()

               #determine if snmp is installed successfully
               s.sendline ('ps aux|grep -v grep|grep snmpd')| s.prompt()
               if "/dev/null" in s.before:
                   print "  SUCCESS"
               else: 
                   print "  FAILED (snmpd is NOT running)"
    #------------------------------------

    print "\n********************** DONE *******************************"

except  mdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])
    sys.exit(1)


finally:
    if con:
         con.close()