#! /usr/bin/python

import os
import time
from subprocess import Popen, PIPE
import platform

def execAndWait(cli_str):
   print '    EXEC:', cli_str
   process = Popen(cli_str, shell=True)
   while process.poll() == None:
      time.sleep(0.01)

# Ubuntu 10.10+ has issues with the regular gconftool-2 commands
# for registering URL handlers.  Need a different solution, but 
# it's a permanent one.
perm_app_register = True


def createDesktopFile(name, idstr, arglist, toDir=''):
   toPath = os.path.join(toDir, 'armory%s.desktop' % idstr) 
   deskfile = open(toPath, 'w')
   deskfile.write('[Desktop Entry]\n')
   deskfile.write('Type=Application\n')
   deskfile.write('Name=Armory')
   if name:
      deskfile.write(' (' + name + ')')
   deskfile.write('\n')
   deskfile.write('GenericName=Bitcoin Client\n')
   deskfile.write('Comment=Full-featured Bitcoin wallet management application\n')
   deskfile.write('Categories=Qt;Network;\n')
   deskfile.write('Exec=python /usr/lib/armory/ArmoryQt.py')
   for a in arglist:
      deskfile.write(' --%s' % a)
   if perm_app_register:
      deskfile.write(' %u')
   deskfile.write('\n')
   deskfile.write('Icon=armory%sicon\n' % idstr)
   deskfile.write('StartupNotify=false\n')
   deskfile.write('Terminal=false\n')
   deskfile.write('MimeType=x-scheme-handler/bitcoin\n')
   deskfile.close()


# Give the system time to actually get rid of the .desktop files
time.sleep(1)
createDesktopFile('',            '',       [],         '/usr/share/applications')
createDesktopFile('Offline',     'offline',['offline'],'/usr/share/applications')
createDesktopFile('Test Network','testnet',['testnet'],'/usr/share/applications')

print '   Setting up menu items.'
execAndWait('xdg-icon-resource install --novendor --context apps --size 64 /usr/share/armory/img/armory_icon_64x64.png armoryicon')
execAndWait('xdg-icon-resource install --novendor --context apps --size 64 /usr/share/armory/img/armory_icon_64x64.png armoryofflineicon')
execAndWait('xdg-icon-resource install --novendor --context apps --size 64 /usr/share/armory/img/armory_icon_green_64x64.png armorytestneticon')
execAndWait('xdg-desktop-menu  install --novendor /usr/share/applications/armory.desktop')
execAndWait('xdg-desktop-menu  install --novendor /usr/share/applications/armorytestnet.desktop')
execAndWait('xdg-desktop-menu  install --novendor /usr/share/applications/armoryoffline.desktop')
print ''
print '!!! Armory installed successfully !!!'
print ''
print '  Armory can be removed at any time, either through your package '
print '  manager, or through the following command:'
print '      sudo dpkg -r armory'


