#!/usr/bin/env python

import os
cur_path = os.path.split(os.path.realpath(__file__))[0]

os.chdir(cur_path)

version = open("node_modules/salvus_version.js").read().split('=')[1].strip()

#### "--all" disables caching ####

import sys

if '--all' in sys.argv:
    all = True
    sys.argv.remove("--all")
else:
    all = False

##################################
# generate static/index.html

out = open("static/index.html","w")
## removed since this has to be after doctype...
## out.write("<!-- THIS FILE IS AUTOGENERATED BY gen_page !!! Edit the files in static/page instead. -->\n\n")

for X in open("page/index.html").readlines():
    if ".html" in X:
       out.write(open(os.path.join("page/", X.strip())).read().replace("__SALVUS_VERSION__",version))
    else:
       out.write(X)

####################################################
# generate static/index.js and static/index.min.js

out = open("static/index.js","w")
out.write("/* THIS FILE IS AUTOGENERATED BY gen_page !!! Edit the files in static/page instead. */\n\n")
out.write("""
$(function() {

/* A very simple implementation of require for the page modules. */
var _require = require;
_require.page_modules = {};
require = function(name) {
    var m = _require.page_modules[name];  /* check if it is a page module */
    if (m != null) { return m; }          /* yes */
    return _require(name);                /* no: use the browserify require -- which wraps npm modules */
};
var key;
for (key in _require) { require[key] = _require[key]; }  /* copy over the other functionality of require module */
""")

for X in open("page/index.js").readlines():
    Y = X.strip()
    base, ext = os.path.splitext(Y)
    if Y.startswith('#'):
        # ignore comments
        pass
    elif ext == '.coffee' or ext == '.cjsx':
        out.write("exports={};(function(){\n")
        out.write(open(os.path.join("page/temp/", Y.replace(ext,'.js'))).read())
        out.write("})();_require.page_modules['%s']=exports;"%base)
    else:
        out.write(X)

out.write("\n});")
out.close()

####################################################
# generate static/index.css

# To make the source-map working, we need those .sass files we do this:
# First, copy the .sass in the /static/sass directory,
# the index.sass in /static and only *then* call the node-sass transspiller

IN_SASS = "index.sass"
OUT_CSS = "index.css"
SRC_MAP = "index.map.css"

# sass cmd:
#  -I: the include path for the "_*.sass" include files
#  --no-cache: disables collecting partial results in ".sass-cache/".
#              speeds up processing but might produces stale results when switching branches.
#  --style=compressed: compact CSS without comments, but we want to enable source maps
#  --source-map: only available in sass >= 3.3, i.e. the "node-sass" module
#  -x : don't write source-map into output, we write it on our own

# no_cache = "--no-cache" if all else ""
no_cache = "" # no such option in >= 3.3 ?

os.system("mkdir -p static/sass")
os.system("cp -a page/_*.sass static/sass")
os.system("cp -a page/%s static/%s" % (IN_SASS, IN_SASS))

# we move to static to get the relative paths right -> then back to $path
os.chdir("static")

cmd = "node-sass --include-path sass/ %s --style=compressed --source-map %s -x %s %s" % (no_cache, SRC_MAP, IN_SASS, OUT_CSS)
print("$ " + cmd)
os.system(cmd)
out_sass = open(OUT_CSS, "r").read()
with open(OUT_CSS, "w") as out:
    out.write("/* THIS FILE IS AUTOGENERATED BY gen_page !!! Edit the files in static/page instead. */\n\n")
    out.write(out_sass)
    out.write("\n\n")
    out.write("/*# sourceMappingURL=/static/%s */\n" % SRC_MAP)

# OLD VERSION, replaced by SASS
#out = open("static/index.css","w")
#out.write("/* THIS FILE IS AUTOGENERATED BY gen_page !!! Edit the files in static/page instead. */\n\n")
#for X in open("page/index.css").readlines():
#    if ".css" in X:
#        out.write(open(os.path.join("page/", X.strip())).read())
#    else:
#        out.write(X)

os.chdir(cur_path)

############# END of SASS -> CSS #########################

### Calling wizard's makefile
if all:
    os.system("cd wizard && make -B")
else:
    os.system("cd wizard && make")

