"""
Juypiter theme installer
Author: miraculixx at github.com
# MODIFIED by dunovank at github.com
"""
import argparse
from glob import glob
import os
import sys
import subprocess
ipython_HOME = '~/.ipython/{profile}'
INSTALL_PATH = '~/.ipython/{profile}/static/custom'
INSTALL_JPATH = '~/.jupyter/custom'

THEMES_PATH = os.path.expanduser('~/.jupyter-themes')
DEFAULT_PROFILE = 'default'

def get_themes():
    """ return list of available themes """
    path = THEMES_PATH
    themes = [os.path.basename(theme).replace('.css', '')
              for theme in glob('%s/*.css' % path)]
    return themes

def install_path(profile=None, jupyter=True):
    """ return install path for profile, creates profile if profile does not exist """
    print profile
    paths = []
    actual_path = os.path.expanduser(os.path.join(INSTALL_PATH))
    print profile
    profile = profile or DEFAULT_PROFILE
    actual_path = actual_path.format(profile='profile_'+profile)
    print actual_path
    if not os.path.exists(actual_path):
        print "Profile %s does not exist at %s" % (profile, actual_path)
        print "creating profile: %s" % profile
        subprocess.call(['ipython', 'profile', 'create', profile])
        ipython_HOME = os.path.expanduser(os.path.join(ipython_HOME)).format(profile=profile)
        os.makedirs('/'.join([ipython_HOME, 'static']))
        os.makedirs('/'.join([ipython_HOME, 'static', 'custom']))
        install_path(profile=profile, jupyter=jupyter)
    paths.append(actual_path)

    if jupyter:
        actual_jpath = os.path.expanduser(os.path.join(INSTALL_JPATH))
        if not os.path.exists(actual_jpath):
            os.makedirs(actual_jpath)
        paths.append(actual_jpath)

    return paths

def install_theme(name, profile=None, toolbar=False, jupyter=True):
    """ copy given theme to theme.css and import css in custom.css """
    from sh import cp  # @UnresolvedImport (annotation for pydev)
    source_path = glob('%s/%s.css' % (THEMES_PATH, name))[0]
    paths = install_path(profile, jupyter)

    for i, target_path in enumerate(paths):
        # -- install theme
        themecss_path = '%s/theme.css' % target_path
        customcss_path = '%s/custom.css' % target_path
        cp(source_path, themecss_path)
        cp(source_path, customcss_path)

        print "Installing %s at %s" % (name, target_path)
        # -- check if theme import is already there, otherwise add it
        with open(customcss_path, 'r+a') as customcss:
            if not 'theme.css' in ' '.join(customcss.readlines()):
                customcss.seek(0, os.SEEK_END)
                customcss.write("\n@import url('theme.css');")

        # -- enable toolbar if requested
        if toolbar:
            print "Enabling toolbar"
            with open(themecss_path, 'rs+w') as themefile:
                # TODO do some proper css rewrite
                lines = (line.replace('div#maintoolbar', 'div#maintoolbar_active')
                                  for line in themefile.readlines())
                themefile.seek(0)
                themefile.writelines(lines)
                themefile.truncate()
        else:
            print "Toolbar is disabled. Set -T to enable"


def reset_default(profile=None, jupyter=True):
    """ remove theme.css import """
    from sh import cp  # @UnresolvedImport (annotation for pydev)

    paths = install_path(profile, jupyter)
    for actual_path in paths:
        old = '%s/%s.css' % (actual_path, 'custom')
        old_save = '%s/%s.css' % (actual_path, 'custom_old')
        try:
              cp(old, old_save)
              os.remove(old)
              print "Reset default theme here: %s" % actual_path
        except Exception:
              print "Already set to default theme in %s" % actual_path
              pass

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-t', "--theme", action='store',
                        help="the name of the theme to install")
    parser.add_argument('-l', "--list", action='store_true',
                        help="list available themes")
    parser.add_argument('-r', "--reset", action='store_true',
                        help="reset to default theme")
    parser.add_argument('-T', "--toolbar", action='store_true',
                        default=False,
                        help="if specified will enable the toolbar")
    parser.add_argument('-J', "--jupyter", action='store_true',
                        default=False,
                        help="install for jupyter (ipython 4.X+)")
    parser.add_argument('-p', "--profile", action='store',
                        default=DEFAULT_PROFILE,
                        help="set the profile, defaults to %s" % DEFAULT_PROFILE)
    args = parser.parse_args()

    if args.list:
        themes = get_themes()
        print "Themes in %s" % THEMES_PATH
        print '\n'.join(themes)
        exit(0)
    if args.theme:
        themes = get_themes()
        if args.theme not in themes:
            print "Theme %s not found. Available: %s" % (args.theme,
                                                         ' '.join(themes))
            exit(1)
        install_theme(args.theme, profile=args.profile, toolbar=args.toolbar, jupyter=args.jupyter)
        exit(0)
    if args.reset:
        reset_default(profile=args.profile, jupyter=args.jupyter)

@@ -173,28 +173,27 @@
 process%0A
-ipython_HOME
+IPHOME_PATH
  = '~/.i
@@ -823,24 +823,88 @@
 TALL_PATH))%0A
+    actual_home = os.path.expanduser(os.path.join(IPHOME_PATH))%0A
     print pr
@@ -1277,93 +1277,70 @@
    i
-python_HOME = os.path.expanduser(os.path.join(ipython_HOME)).format(profile=profile)%0A
+f not os.path.exists('/'.join(%5Bactual_home, 'static'%5D)):%0A     
     
@@ -1361,36 +1361,35 @@
 s('/'.join(%5B
-ipython_HOME
+actual_home
 , 'static'%5D)
@@ -1386,24 +1386,29 @@
 'static'%5D))%0A
+     
         os.m
@@ -1429,20 +1429,19 @@
 in(%5B
-ipython_HOME
+actual_home
 , 's

fix inf loop during install on ipython4