#!/usr/bin/python3

import os
import sys
import codecs

if len(sys.argv) < 3:
	print(f'Usage:\n{sys.argv[0]} venvname port')
	sys.exit(1)

user = os.getlogin()
home = os.environ.get('HOME')
try:
	os.mkdir(f'{home}/ve')
except:
	pass

venv = sys.argv[1]
port = int(sys.argv[2])
os.system(f'python3 -m venv ~/ve/{venv}')
pwd = os.getcwd()
name = os.path.basename(pwd)
if os.path.exists(f'./app/{name}.py'):
	print('env exists')
	sys.exit(1)

dirs = f'./app ./conf ./files ./wwwroot ./script ./logs'.split(' ')
for d in dirs:
	try:
		os.mkdir(d)
	except:
		pass
files=f'app/{name}.py conf/config.json files/README.md wwwroot/index.dspy'.split(' ')
for f in files:
	os.system(f'touch {f}')

config_str=f"""
{{
    "logger":{{
        "name":"{name}",
        "levelname":"info",
        "logfile":"$[workdir]$/logs/sage.log"
    }},
    "filesroot":"$[workdir]$/files",
    "website":{{
        "paths":[
            ["$[workdir]$/wwwroot",""]
        ],
        "client_max_size":10000,
        "host":"0.0.0.0",
        "port":{port},
        "coding":"utf-8",
        "indexes":[
            "index.html",
            "index.tmpl",
            "index.ui",
            "index.dspy",
            "index.md"
        ],
        "startswiths":[
            {{
                "leading":"/idfile",
                "registerfunction":"idFileDownload"
            }}
        ],
        "processors":[
            [".dspy","dspy"],
            [".md","md"]
        ],
        "session_max_time":3000,
        "session_issue_time":2500,
        "session_redis_notuse":{{
            "url":"redis://127.0.0.1:6379"
        }}
    }},
    "langMapping":{{
        "zh-Hans-CN":"zh-cn",
        "zh-CN":"zh-cn",
        "en-us":"en",
        "en-US":"en"
    }}
}}
"""
service = f"""[Unit]
Description={name} service
Wants=systemd-networkd.service
Requires=nginx.service

[Service]
Type=forking
ExecStart=su - {user} -c "{pwd}/script/{name}.sh"
ExecStop=su - ymq "{home}/bin/killname {name}.py"
[Install]
WantedBy=multi-user.target
"""

with codecs.open(f'./script/{name}.service', 'w', 'utf-8') as f:
	f.write(service)

with codecs.open(f'./script/{name}.sh', 'w', 'utf-8') as f:
	f.write(f"""#!/usr/bin/bash

killname {pwd}/app/{name}.py
{home}/ve/{venv}/bin/python {pwd}/app/{name}.py -w {pwd} > {pwd}/logs/stderr.log 2>&1 &
exit 0
""")

with codecs.open(f'./script/install.sh', 'w', 'utf-8') as f:
	f.write(f"""#!/usr/bin/bash
sudo cp {name}.service /etc/systemd/system
sudo systemctl enable {name}.service
sudo systemctl start {name}
""")

od.system('chmod +x script/*.sh')

with codecs.open(f'./conf/config.json', 'w', 'utf-8') as f:
	f.write(config_str)

with codecs.open(f'./requirements.txt', 'w', 'utf-8') as f:
	f.write("""git+https://git.kaiyuancloud.cn/yumoqing/apppublic
git+https://git.kaiyuancloud.cn/yumoqing/sqlor
git+https://git.kaiyuancloud.cn/yumoqing/ahserver
""")

if not os.path.exists(f'{home}/bin'):
	os.mkdir(f'{home}/bin')
if not os.path.exists(f'{home}/bin/killname'):
	with codecs.open(f'{home}/bin/killname', 'w', 'utf-8') as f:
		f.write("""#!/usr/bin/bash

ps -ef|grep "$1"|grep -v grep|awk '{print("kill -9", $2)}'|sh
""")
with codecs.open(f'{home}/bin/{venv}py', 'w', 'utf-8') as f:
	f.write(f"""#!/usr/bin/bash

~/ve/{venv}/bin/python $*
""")
with codecs.open(f'{home}/bin/{venv}pip', 'w', 'utf-8') as f:
	f.write(f"""#!/usr/bin/bash

~/ve/{venv}/bin/pip $*
""")

os.system(f'chmod +x {home}/bin/{venv}*')