""" build a distribution with py2exe or py2app."""

from distutils.core import setup
import os
import sys
import platform
from datetime import date

#---------------------------------------------------------------

def recursive_files(root, exclude):
  dirlist = os.listdir(root)
  pathfilelist = []
  myfilelist = []
  for file_dir in dirlist:
    file_dirpath = os.path.join(root, file_dir)
    (stem, ext) = os.path.splitext(file_dir)
    if (ext.lower() not in exclude):
      if os.path.isdir(file_dirpath):
          subdirlist = recursive_files(file_dirpath, exclude)
          pathfilelist.extend(subdirlist)
      elif os.path.isfile(file_dirpath):
         myfilelist.append(file_dirpath)
  if len(myfilelist) > 0:
      pathfilelist.insert(0, (root, myfilelist))
  return pathfilelist

#---------------------------------------------------------------

data = recursive_files("data", [".svn"])
start_script = "stegavorto.py"
game_name = "StegaVorto"
game_description = "The Magical Word Game That Came To James In A Dream"
win_icon = "icons/win_icon.ico"
mac_icon = "icons/mac_icon.icns" # this doesn't work for reasons I don't understand :( 
game_version = date.today().strftime("%Y.%m.%d")
excluded = "_dotblas,pygame.sndarray,multiarray,pygame.surfarray,smpeg,numpy,email"

terse_plat_string = platform.platform(aliased = True, terse = True)

if 'Windows' in terse_plat_string:
  import py2exe
  sys.argv[1:] = ["py2exe", "-O0", "-b", "1"]
  platform_options = {"py2exe":{"optimize":2, "excludes":excluded}}
  setup(
      version = game_version,
      description = game_description,
      name = game_name,
      data_files = data,
      windows = [{"script":start_script, "icon_resources": [(1, win_icon)]}],
      options = platform_options
      )

elif 'Darwin' in terse_plat_string:
  import py2app
  sys.argv[1:] = ["py2app", "--excludes", excluded]
  platform_options = dict(py2app=dict(argv_emulation=True,
                                 iconfile=mac_icon,
                                 plist=dict(CFBundleIconFile=os.path.basename(mac_icon))
                                 ))
  setup(
      version = game_version,
      description = game_description,
      name = game_name,
      data_files = data,
      app = [start_script],
      options = platform_options
      )
  print "Now bundle app into a dmg"
  os.system("""mkdir '%(name)s'
               mv 'dist/%(name)s.app' '%(name)s/'
               rm '%(name)s.dmg'
               hdiutil create -srcfolder '%(name)s' '%(name)s.dmg'
               rm -R '%(name)s'
               mv %(name)s.dmg dist/
            """ % {"name" : game_name})

else:
  print 'ERROR: your platform',platform.platform(aliased = True, terse = True),'has no build configuration written'
  raise SystemExit
