#!/usr/bin/env python
import time

# TODO: All keys in /usr/lib/systemd/systemd --dump-config
env = r['env']

da_run = '%(env.DA_DIR_DEVAPPS)s/bin/run --source_env \\\n'
da_run += '"%(env.DA_DIR)s/build/%(env.DA_CLS)s" '


def upper_camel(s):
    pre, s = s.split('_', 1)
    r = []
    for p in s.split('_'):
        # send_SIGKILL
        if p[0] == p[0].upper():
            r.append(p)
        else:
            r.append(p.capitalize())
    r = ''.join(r)
    # stop_post_1:
    if r[-1].isdigit():
        r = r[:-1]
    return r


out.append(
    """
[Unit]
Description      = %(unit_description)s
Wants            = network-online.target
StopWhenUnneeded = %(unit_stop_when_unneeded)s

[Service]
Type        = %(service_type)s
"""
)

svc = [k for k in env if k.startswith('service_') and not k == 'service_type']
svc = sorted(svc)
for k in svc:
    v = env[k]
    if k.startswith('service_exec_'):
        if not 'app' in r['env']:
            # no more:
            raise Exception('Not supported: no app in env')
            # v = da_run + '\\\n' + v
        v = v.replace('--flagfile', '\\\n--flagfile')
        # otherwise our da_run eval fails, see nginx's '-g daemon off':
        v = v.replace("'", "\\'")
        if not v.startswith('/'):
            v = r['env']['app_run_script_path'] + ' ' + v
    K = upper_camel(k)
    out.append('%s=%s' % (K, v))


out.append('SyslogIdentifier=%(name)s')
out.append('')
out.append(
    """
[Install]
WantedBy = devapps.target
WantedBy = default.target

""".lstrip()
    + """
# Autogenerated by devapps spec run at %s
#
"""
    % time.ctime()
)
