import xbmc, xbmcgui, xbmcaddon, sys, os

# Read settings
__addon__ = xbmcaddon.Addon( id="script.synology.poweroff" )
language  = __addon__.getLocalizedString

# Notification settings
enableLaunchNotifies = __addon__.getSetting("enableLaunchNotifies")
enableHostupNotifies = __addon__.getSetting("enableHostupNotifies")
enableErrorNotifies = __addon__.getSetting("enableErrorNotifies")

# Set icons
rootDir = __addon__.getAddonInfo('path')
if rootDir[-1] == ';':rootDir = rootDir[0:-1]
resDir = os.path.join(rootDir, 'resources')
iconDir = os.path.join(resDir, 'icons')
iconConnect = os.path.join(iconDir, 'server_connect.png')
iconError = os.path.join(iconDir, 'server_error.png')
iconSuccess = os.path.join(iconDir, 'server.png')

def checkLibrary(module_name):
  try:
    __import__(module_name)
    print("\tLibrary '%s' successfully loaded!" % module_name)
  except ImportError as e:
    print("\tError: Unable to load the library '%s'!" % module_name)
    print(e)
    if (enableErrorNotifies == "true"):
      xbmc.executebuiltin('XBMC.Notification("'+language(59000) +'","'+language(59001) % module_name +'",5000,"'+iconError+'")')

    exit()
    sys.exit(1)


def start():
  __addonid__      = __addon__.getAddonInfo('id')
  __addonname__    = __addon__.getAddonInfo('name')
  print("%s: Starting %s" % (__addonid__, __addonname__))


def exit():
  __addonid__      = __addon__.getAddonInfo('id')
  __addonname__    = __addon__.getAddonInfo('name')
  print("%s: Closing %s" % (__addonid__, __addonname__))


def log(stream):
  for line in stream:
    print("\t%s" % line)


def main(isAutostart=False):    
  start()

  # Basic settings
  ipaddress       = __addon__.getSetting("ipaddress")
  hostname        = __addon__.getSetting("hostname")
  username        = __addon__.getSetting("username")
  password        = __addon__.getSetting("password")
  poweroff_cmd    = __addon__.getSetting("poweroff_cmd")

  # Check the required libraries
  protocole = int(__addon__.getSetting("protocole"))
  if protocole == 0:
    checkLibrary('paramiko')
    import paramiko
  else:
    import telnetlib

  # Call the poweroff command on the (remote) machine
  try:
    # Send Connection Notification via SSH
    if (enableLaunchNotifies == "true"):
      xbmc.executebuiltin('XBMC.Notification("'+language(60000).replace("%hostname%",hostname)+'","",10000,"'+iconConnect+'")')

    if protocole == 0:
      ssh = paramiko.SSHClient()
      ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
      ssh.connect(hostOrIp, username=username, password=password)

#      xbmc.executebuiltin('XBMC.Notification("SSH successfully connected!","",5000,"'+iconConnect+'")')
      print("\tTelnet successfully connected!")

      stdin, stdout, stderr = ssh.exec_command(poweroff_cmd)
      log(stdout)
      log(stderr)

#      xbmc.executebuiltin('XBMC.Notification("Power off command successfully sent!","",5000,"'+xbmc.translatePath(__addon__.getAddonInfo('path') + "/icon.png")+'")')
      print("\tPower off command successfully sent!")
      ssh.close()

    # Send Connection Notification via Telnet
    else:
      tn = telnetlib.Telnet()
      tn.open(ipaddress, timeout=5)

#      xbmc.executebuiltin('XBMC.Notification("Telnet successfully connected!","",5000,"'+iconConnect+'")')
      print("\tTelnet successfully connected!")
      xbmc.sleep(5000)

      tn.read_until(hostname + " login: ", timeout=5)
      tn.write(username + "\n")
      if password:
        tn.read_until("Password: ", timeout=5)
        tn.write(password + "\n")
#        xbmc.executebuiltin('XBMC.Notification("Credentials ('+ username + ':'+ password + ') successfully provided to '+ hostname + '!","",5000,"'+xbmc.translatePath(__addon__.getAddonInfo('path') + "/icon.png")+'")')

      print("\tCredentials successfully provided!")
      xbmc.sleep(1000)

      tn.write(poweroff_cmd + "\n")
#      xbmc.executebuiltin('XBMC.Notification("Power off command successfully sent!","",5000,"'+xbmc.translatePath(__addon__.getAddonInfo('path') + "/icon.png")+'")')
      print("\tPower off command successfully sent!")
      xbmc.sleep(5000)
#      tn.write("exit\n")
      tn.close()

    if (enableHostupNotifies == "true"):
      xbmc.executebuiltin('XBMC.Notification("'+language(59004).replace("%hostname%",hostname)+'","",5000,"'+iconSuccess+'")')

  except Exception as e:
    print(e)
    if (enableHostupNotifies == "true"):
      xbmc.executebuiltin('XBMC.Notification("'+language(59002) +'","'+ language(59003) + " " + str(e)+'",5000,"'+iconError+'")')
#      xbmcgui.Dialog().ok(language(59002), language(59003) + " " + str(e))

  exit()


if __name__ == '__main__':
  main()
