#!/usr/bin/python3

import argparse
import getpass
import os
import subprocess

# # only needed to find the library directory
import docing
from pathlib import Path
#import server
# import sys

# from nitpo import Nitpo
from runic import Runic
desc = 'install via socket'
parser = argparse.ArgumentParser(description=desc)
# parser.add_argument('-s', action='store_true', help='stop only')
args = parser.parse_args()

r = Runic()

if not r.has_conf('files', 'socket'):
    print("I need a socket file configure")
    quit()

user = os.getlogin()
lib_fudi = os.path.dirname(os.path.abspath(docing.__file__))
bin_fudi = os.path.dirname(lib_fudi) + '/bin'
home_dir = os.environ['HOME']

if not r.has_conf('files','socket'):
    print("I need a socket file defined")
socket_fufi = r.conf['files']['socket']

if not r.has_conf('folders','web_log'):
    print("I need a socket file defined")
log_dir = r.conf['folders']['web_log']

socket_text = ''
socket_text += "[Unit]\nDescription=nitpo socket\n\n[Socket]\n"
socket_text += f"ListenStream={socket_fufi}\n"
socket_text += "SocketMode=0777\n"
socket_text += "SocketUser=ernad\n\n"
socket_text += "[Install]\nWantedBy=sockets.target\n\n"
systemd_fudi = home_dir + '/.config/systemd/user'
if not os.path.isdir(systemd_fudi):
    Path(systemd_fudi).mkdir(parents=True, exist_ok=True)

systemd_fufi = systemd_fudi + '/nitpo.socket'
systemd_file = open(systemd_fufi, 'w')
systemd_file.write(socket_text)
systemd_file.close()

system_text = ''
system_text += "[Unit]\nDescription=nitpo service\n"
system_text += "Requires=nitpo.socket\nAfter=network.target\n\n"
system_text += f'[Service]\nEnvironment="PYTHONPATH={lib_fudi}"\n'
system_text += "Type=notify\n"
# system_text += f"User={user}\nGroup={user}\n"
system_text += "ExecStart=/usr/bin/gunicorn --capture-output"
system_text += f" --log-file {log_dir}/out"
system_text += f" --error-logfile {log_dir}/err"
system_text += f" --access-logfile {log_dir}/log"
system_text += f" -c {lib_fudi}/gunicorn.py server:app\n"
system_text += 'ExecReload=/bin/kill -s HUP $MAINPID\n'
system_text += "KillMode=mixed\nTimeoutStopSec=5\nPrivateTmp=true\n\n"
system_text += "[Install]\nWantedBy=sockets.target\n"


#print(socket_text)#
#
#quit()

#print(system_text)
#quit()

systemd_fufi = systemd_fudi + '/nitpo.service'
systemd_file = open(systemd_fufi, 'w')
systemd_file.write(system_text)
systemd_file.close()

#subprocess.run("/bin/systemctl --user --now enable nitpo", check=True, shell=True)
subprocess.run("/bin/systemctl --user --now enable nitpo.socket", check=True, shell=True)
#subprocess.run("/bin/systemctl --user start nitpo.socket", check=True, shell=True)
#subprocess.run("/bin/systemctl --user start nitpo.service", check=True, shell=True)


quit()
print(getpass.getuser())