'''
This script will run everytime frostwire is launched. It'll check if there are
any .pack files the frostwire installation folder. It'll unpack them and then
it'll update the hashes file, so that frostwire can start.
'''
import os
INSTDIR='/usr/lib/frostwire'    
def makeHashes():
  #creates the hashes based on the md5s of all the jars
  import md5

  #Get the path to the installation dir
  #and work inside it
  os.chdir(INSTDIR)
  localFiles = os.listdir(".")

  output = file('hashes','w')

  for f in localFiles:
    if f.endswith('.jar'):
      fp = file(f,'rb')
      line = f + "=" + str(md5.new(fp.read()).hexdigest()).upper()
      fp.close()
      output.write(line + "\n")
      print line

  output.close()

def thereArePacks():
  os.chdir(INSTDIR)
  packsFound = 0

  for f in os.listdir(INSTDIR):
    if f.endswith('.pack'):
      packsFound += 1
      break

  return packsFound > 0

def unpack200():
  os.chdir(INSTDIR)
  
  for f in os.listdir(INSTDIR):
    if f.endswith('.pack'):
      file_name_no_ext = f[0:f.find('.pack')]
      unpack_cmd = 'unpack200 --quiet %s %s' % (f,
                                                file_name_no_ext + '.jar')

      os.system(unpack_cmd)

      #remove the pack, if and only if the equivalent .jar exists
      if os.path.exists(file_name_no_ext + '.jar'):
        os.remove(f)

if __name__ == "__main__":      
    if thereArePacks():
      unpack200()
      makeHashes()
