#!/usr/bin/python

import sys, os, xbmc, xbmcgui, xbmcplugin, shutil, urllib, urllib2, unicodedata, re, time, subprocess

dp = xbmcgui.DialogProgress()
dialog = xbmcgui.Dialog()
all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = ''.join(map(unichr, range(0,32) + range(127,160)))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
useragent='OSMC'

def upggmc(silent):
 ACTION_PREVIOUS_MENU = 10
 rupgfile = 'http://repo.galaxymediaonline.com/System_Upgrades/currentversion'
 lupgfile = '/mnt/sda2/update/upgradeversion'
 loc = urllib.URLopener()
 if os.path.isfile('/mnt/sda2/update/menuupgradeversion'):
  os.remove('/mnt/sda2/update/menuupgradeversion')
 if os.path.isfile('/mnt/sda2/update/upgradeversion'):
  os.remove('/mnt/sda2/update/upgradeversion')
 if os.path.isfile('//mnt//sda2//update//updatestatus'):
  os.remove('//mnt//sda2//update//updatestatus')
 if not silent == 'silent':
  dp.create("Galaxy System Update","","","Checking for updates...")
 xbmc.log("GMCsystemupdate update check initiated. %s" % time.time(), level=xbmc.LOGDEBUG)
 sts=0
 try:
  loc.retrieve(rupgfile, lupgfile)
 except:
  xbmc.log("GMCsystemupdate cannot connect to server. Update failed. %s" % time.time(), level=xbmc.LOGERROR)
  if not silent == 'silent':
   dialog.ok('GMC System Update','','Cannot connect to server.','Update failed.'+silent)
  _exitout()
 GMCV = next(open('//home/osmc//currentversion'))
 upgv=next(open('//mnt//sda2//update//upgradeversion'))
 gmcv=remove_control_chars(GMCV)
 upgv=remove_control_chars(upgv)
 url='http://repo.galaxymediaonline.com//System_Upgrades//GMCv'+upgv+'.tar.gz'
 if gmcv == upgv:
  if not silent == 'silent':
   dp.close()
  xbmc.log("GMCsystemupdate v"+upgv+" is current. %s" % time.time(), level=xbmc.LOGNOTICE)
  if not silent == 'silent':
   dialog.ok('Galaxy System Upgrade',' ','Your version '+upgv+' is current')
  sts=1
 else:
  dialog.notification('', 'Galaxy Media Center version '+upgv+' is available', xbmcgui.NOTIFICATION_INFO, 10000)
  if not silent == 'silent':
   dp.close()
  i = dialog.yesno("Galaxy System Update","","New version "+upgv+" is available","Install update now?","Cancel","Install")
  xbmc.log("GMCsystemupdate new version "+upgv+" found.  Prompting for install. %s" % time.time(), level=xbmc.LOGNOTICE)
  if i == 0:
   if not silent == 'silent':
    dp.close()
   xbmc.log("GMCsystemupdate download cancelled. Update failed. %s" % time.time(), level=xbmc.LOGWARNING)
   dialog.ok("Galaxy System Update"," ","Update Cancelled")
   time.sleep(5)
   _exitout()
  else:
   sts = 2
   try:
    req=urllib2.urlopen(url, useragent)
   except urllib2.HTTPError, e:
    errc=str(e.code)
    xbmc.log("GMCsystemupdate update file does not exist to download. Update failed. %s" % time.time(), level=xbmc.LOGERROR)
    dialog.ok('GMC System Update','','Error downloading update.','Update failed.')
    _exitout()
 if sts == 2:
  dp.create("Downloading"," ","Downloading system update...")
  loc.retrieve(url,'//mnt//sda2//update//GMCUPDATE.tar.gz',lambda nb, bs, fs, url=url: _pbhook(nb,bs,fs,url,dp))
  if os.path.isfile('//mnt//sda2//update//GMCUPDATE.tar.gz'):
   doupgrade(upgv)
  else:
   xbmc.log("GMCsystemupdate cannot find local update file. Update failed. %s" % time.time(), level=xbmc.LOGERROR)
   if not silent == 'silent':
    dp.close()
   dialog.ok('GMC System Update','','Error downloading update.','Update failed.')
   _exitout()
 choco=0
 try:
  loc.retrieve('http://repo.galaxymediaonline.com//System_Upgrades//menuversion', '//mnt//sda2//update//menuupgradeversion')
 except:
  xbmc.log("GMCsystemupdate cannot connect to server. Settings update failed. %s" % time.time(), level=xbmc.LOGERROR)
  if not silent == 'silent':
   dialog.ok('GMC System Update','','Error downloading settings update','Update failed.')
  _exitout()
 menuv = next(open('//home//osmc//menuversion'))
 mupgv = next(open('//mnt//sda2//update//menuupgradeversion'))
 menuv=remove_control_chars(menuv)
 mupgv=remove_control_chars(mupgv)
 url='http://repo.galaxymediaonline.com//System_Upgrades//GMCMENUUPDATE.tar.gz'
 if menuv == mupgv:
  xbmc.log("GMCsystemupdate settings v"+mupgv+" is current. %s" % time.time(), level=xbmc.LOGNOTICE)
  if not silent == 'silent':
   if not sts == 2:
    dialog.ok('Galaxy System Update',' ','No settings updates available.')
 else:
  xbmc.log("GMCsystemupdate new settings v"+mupgv+" found.  Installing. %s" % time.time(), level=xbmc.LOGNOTICE)
  try:
   req=urllib2.urlopen(url, useragent)
  except urllib2.HTTPError, e:
   errc=str(e.code)
   xbmc.log("GMCsystemupdate Error downloading settings update. Settings update failed. %s" % time.time(), level=xbmc.LOGERROR)
   if not silent == 'silent':
    dialog.ok('GMC System Update','','Error downloading settings update.','Update Failed.')
   _exitout()
  if not sts == 2:
   dp.create("Downloading"," ","Downloading settings update...")
  url='http://repo.galaxymediaonline.com//System_Upgrades//GMCMENUUPDATE.tar.gz'
  loc.retrieve(url,'//mnt//sda2//update//GMCMENUUPDATE.tar.gz',lambda nb, bs, fs, url=url: _pbhook(nb,bs,fs,url,dp))
  subprocess.Popen(['/usr/bin/sudo', '/home/osmc/.kodi/addons/script.gmcsystemupdate/subprocmenuupg'])
  time.sleep(5)
  os.remove("//home/osmc//menuversion")
  shutil.move("//mnt//sda2//update//menuupgradeversion", "//home/osmc//menuversion")
  xbmc.log("GMCsystemupdate new settings v"+mupgv+" has been installed. %s" % time.time(), level=xbmc.LOGNOTICE)
  choco=1
 if sts == 2:
  dp.close()
  dp.create("Galaxy System Update","Refreshing Interface","Please wait...")
  xbmc.log("GMCsystemupdate Refreshing interface... %s" % time.time(), level=xbmc.LOGNOTICE)
  if os.path.isfile('/mnt/sda2/update/menuupgradeversion'):
   os.remove('/mnt/sda2/update/menuupgradeversion')
  if os.path.isfile('/mnt/sda2/update/upgradeversion'):
   os.remove('/mnt/sda2/update/upgradeversion')
  if os.path.isfile('//mnt//sda2//update//updatestatus'):
   os.remove('//mnt//sda2//update//updatestatus')
  xbmc.executebuiltin('ReloadSkin')
 if choco == 1:
  if not sts == 2:
   dp.close()
   dp.create("Galaxy System Update","Refreshing Interface","Please wait...")
   xbmc.log("GMCsystemupdate Refreshing interface... %s" % time.time(), level=xbmc.LOGNOTICE)
   if os.path.isfile('/mnt/sda2/update/menuupgradeversion'):
    os.remove('/mnt/sda2/update/menuupgradeversion')
   if os.path.isfile('/mnt/sda2/update/upgradeversion'):
    os.remove('/mnt/sda2/update/upgradeversion')
   if os.path.isfile('//mnt//sda2//update//updatestatus'):
    os.remove('//mnt//sda2//update//updatestatus')
  dp.close()
 _exitout()

def doupgrade(upgv):
  dp.create("Installing Update ","PLEASE DO NOT POWER OFF DEVICE!","This may take awhile. There is no progress indicator yet, the system will reboot when complete. DO NOT TOUCH!")
  dp.update(25)
  p=subprocess.Popen(['/usr/bin/sudo', '/home/osmc/.kodi/addons/script.gmcsystemupdate/subprocupgrade'])
  p.wait()
  dp.update(55)
  dp.close()
  dp.create('GMC System Update','System Update Complete!','Now updating menus and addons then rebooting...','KEEP HOLDING TIGHT')
  dp.update(75)
  os.remove('//home//osmc//currentversion')
  with open("//home//osmc//currentversion", "w") as text_file:
   text_file.write("%s" % upgv)
  xbmc.log("GMCsystemupdate System updated to v"+upgv+" %s" % time.time(), level=xbmc.LOGNOTICE)
  xbmc.executebuiltin('UpdateAddonRepos')
  time.sleep(60)

  if dp.iscanceled():
   dp.create("Installing Update ","PLEASE DO NOT POWER OFF DEVICE!","This may take awhile. THERE IS NO CANCELLING THIS.","JUST WAIT...")
   dp.update(50)
   while not upds == "2":
    time.sleep(10)
    upds = next(open('//mnt//sda2//update//updatestatus'))
    upds = remove_control_chars(upds)
   dp.close()
   dp.create('Galaxy System Update','Now updating settings and addons then rebooting...','KEEP HOLDING TIGHT')
   dp.update(75)
   os.remove('//home//osmc//currentversion')
   with open("//home//osmc//currentversion", "w") as text_file:
    text_file.write("%s" % upgv)
   xbmc.log("GMCsystemupdate System updated to v"+upgv+" %s" % time.time(), level=xbmc.LOGNOTICE)
   xbmc.executebuiltin('UpdateAddonRepos')
   time.sleep(60)

def _pbhook(numblocks, blocksize, filesize, url=None,dp=None):
 try:
  percent = min((numblocks*blocksize*100)/filesize, 100)
  print percent
  dp.update(percent)
 except:
  percent = 100
  dp.update(percent)
 if dp.iscanceled():
  xbmc.log("GMCsystemupdate download cancelled. Update failed. %s" % time.time(), level=xbmc.LOGWARNING)
  dialog.ok('GMC System Update','','Download canceled.','Update failed.')
  _exitout()

def _exitout():
 xbmc.log("GMCsystemupdate Script Exiting. %s" % time.time(), level=xbmc.LOGDEBUG)
 if os.path.isfile('/mnt/sda2/update/menuupgradeversion'):
  os.remove('/mnt/sda2/update/menuupgradeversion')
 if os.path.isfile('/mnt/sda2/update/upgradeversion'):
  os.remove('/mnt/sda2/update/upgradeversion')
 if os.path.isfile('//mnt//sda2//update//updatestatus'):
  os.remove('//mnt//sda2//update//updatestatus')
 sys.exit()

def remove_control_chars(s):
 return control_char_re.sub('', s)
