# -*- mode: python -*-
# -*- encoding: utf-8 -*-

import os
import sys
import json
from glob import glob

VS_VERSION_INFO = """
VSVersionInfo(
  ffi=FixedFileInfo(
    # filevers and prodvers should be always a tuple with four
    # items: (1, 2, 3, 4)
    # Set not needed items to zero 0.
    filevers=%(ver_tup)r,
    prodvers=%(ver_tup)r,
    # Contains a bitmask that specifies the valid bits 'flags'r
    mask=0x0,
    # Contains a bitmask that specifies the Boolean attributes
    # of the file.
    flags=0x0,
    # The operating system for which this file was designed.
    # 0x4 - NT and there is no need to change it.
    OS=0x4,
    # The general type of file.
    # 0x1 - the file is an application.
    fileType=0x1,
    # The function of the file.
    # 0x0 - the function is not defined for this fileType
    subtype=0x0,
    # Creation date and time stamp.
    date=(0, 0)
  ),
  kids=[
    StringFileInfo(
      [
      StringTable(
        u'040904E4',
        [StringStruct(u'FileDescription', u'%(name)s'),
        StringStruct(u'FileVersion', u'%(ver_str)s'),
        StringStruct(u'InternalName', u'%(internal_name)s'),
        StringStruct(u'LegalCopyright', u'Copyright © 2015 Yubico'),
        StringStruct(u'OriginalFilename', u'%(exe_name)s'),
        StringStruct(u'ProductName', u'%(name)s'),
        StringStruct(u'ProductVersion', u'%(ver_str)s')])
      ]),
    VarFileInfo([VarStruct(u'Translation', [1033, 1252])])
  ]
)"""

data = json.loads(os.environ['pyinstaller_data'])
data = dict(map(lambda (k, v): (k, v.encode('ascii') if isinstance(v, unicode) else v), data.items()))

DEBUG = bool(data['debug'])
NAME = data['fullname']

WIN = sys.platform in ['win32', 'cygwin']
OSX = sys.platform in ['darwin']

ICON = os.path.join('resources', '%s.png' % data['name'])
if WIN:
    ICON = os.path.join('resources', '%s.ico' % data['name'])
elif OSX:
    ICON = os.path.join('resources', '%s.icns' % data['name'])
if not os.path.isfile(ICON):
    ICON = None

a = Analysis(map(lambda x: x.encode('ascii'), data['scripts']),
             pathex=[''],
             hiddenimports=[],
             hookspath=None,
             runtime_hooks=None)

# DLLs, dylibs and executables should go here.
libs = glob('lib/*')
for filename in libs:
    a.datas.append((filename[4:], filename, 'BINARY'))

# Read version string
ver_str = data['version']

# Read version information on Windows.
VERSION = None
if WIN:
    VERSION = 'build/file_version_info.txt'

    ver_tup = tuple(map(int, ver_str.split('.')))
    # Windows needs 4-tuple.
    if len(ver_tup) < 4:
        ver_tup += (0,) * (4-len(ver_tup))
    elif len(ver_tup) > 4:
        ver_tup = ver_tup[:4]

    # Write version info.
    with open(VERSION, 'w') as f:
        f.write(VS_VERSION_INFO % {
            'name': NAME,
            'internal_name': data['name'],
            'ver_tup': ver_tup,
            'ver_str': ver_str,
            'exe_name': '%s.exe' % NAME
        })

pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name=NAME if not WIN else '%s.exe' % NAME,
          debug=DEBUG,
          strip=None,
          upx=True,
          console=DEBUG,
          append_pkg=not OSX,
          version=VERSION,
          icon=ICON)

# Sign the executable
if WIN:
        os.system("signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll \"%s\"" %
                  (exe.name))

coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=None,
               upx=True,
               name=NAME)

# Create .app for OSX
if OSX:
    app = BUNDLE(coll,
                 name="%s.app" % NAME,
                 version=ver_str,
                 icon=ICON)

    with open('dist/%s.app/Contents/Resources/qt.conf' % NAME) as f:
        f.write('[Path]\nPlugins = plugins')

# Create Windows installer
if WIN:
    installer_cfg = 'resources/win-installer.nsi'
    if os.path.isfile(installer_cfg):
        os.system('makensis.exe -D"VERSION=%s" %s' % (ver_str, installer_cfg))
        installer = "dist/%s-win.exe" % data['ver_name']
        os.system("signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll \"%s\"" %
                 (installer))
        print "Installer created: %s" % installer

@@ -76,16 +76,29 @@
 rt json%0A
+import errno%0A
 from glo
@@ -3775,26 +3775,26 @@
 N)%0A%0A    
-with open(
+qt_conf = 
 'dist/%25s
@@ -3832,16 +3832,237 @@
 ' %25 NAME
+%0A    qt_conf_dir = os.path.dirname(qt_conf)%0A    try:%0A        os.makedirs(qt_conf_dir)%0A    except OSError as e:%0A        if e.errno != errno.EEXIST or os.path.isdir(qt_conf_dir):%0A            raise%0A    with open(qt_conf, 'w'
 ) as f:%0A

Fix again.