#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import argparse
# import asyncio
import getpass
# import hmac
import importlib
# import json
# import logging
import logging.config
import os
import pwd
# import shlex
import subprocess
import sys
# import threading
import time
from pathlib import Path

# from dotenv import load_dotenv
import stem.process
from flask import Flask, jsonify, render_template, request
from flask_restful import Api, Resource
from flask_settings import Settings
from stem.control import Controller
from stem.util import term

from mtlibs import github, mtutils, process_helper, tor_helper
from mtlibs.process_helper import exec

# 系统常量
HTTP_PORT = os.environ.get("HTTP_PORT", 80)
TORCONTROLL_PASSWORD = "my_password"
TOR_CONTROLL_PORT = 9051
TOR_SOCKS_PORT = 9050

os.environ["NOTTOR_USER"] = NOTTOR_USER = 'nottor'
GHTOKEN = os.environ.get("GHTOKEN", None)
os.environ["TOR_CONTROLL_PORT"] = str(TOR_CONTROLL_PORT)
os.environ["TORCONTROLL_PASSWORD"] = TORCONTROLL_PASSWORD
os.environ["API_TOKEN"] = API_TOKEN = os.environ.get(
    'API_TOKEN', 'ijs79/ksj^@))jsJKo!mnv09Pox6yanU87H7Xjs_))(++xsia')


def start_github_default():
    """部署默认仓库源码"""
    startup_repo = os.environ.get("MT_STARTUP_GITHUBREPO", None)
    if startup_repo:
        print("运行起始仓库 %s" % startup_repo)
        github.deploy_repo(startup_repo)


def start_direct_socksserver():
    """提供能直接连接外网的网络代理"""
    print(term.format("启动 direct socks5 server 服务", term.Color.RED),
          flush=True)
    os.system('cp -r ~/.config/clash /tmp/clash')
    os.system(
        'sudo -u debian-tor curl --insecure https://116.202.120.181/api/ip')
    os.system(
        "sudo -u debian-tor clash -d /tmp/clash -f /tmp/clash/config_direct.yaml &"
    )


def repo_deploy():
    """
        部署源码
    """
    startup_repo = os.environ.get("REPO_RUN", None)
    print(term.format("启动 repo_deploy %s" % startup_repo, term.Color.RED),
          flush=True)
    if startup_repo:
        print(term.format("REPO %s" % startup_repo, term.Color.YELLOW),
              flush=True)
        github.deploy_repo(startup_repo)


def setup_args_options():
    """设置命令行参数"""
    parser = argparse.ArgumentParser()
    parser.add_argument("test",
                        type=int,
                        help="display a square of a given number")
    parser.add_argument("--verbose",
                        help="increase output verbosity",
                        action="store_true")


def save_ed25519_private_key(key_text):
    """保存私钥文件"""
    file = os.path.expanduser('~/.ssh/id_ed25519')
    if not os.path.exists(file):
        Path(file).parent.mkdir(parents=True, exist_ok=True)
        # Path(file).touch(exist_ok=True)
        with open(file, 'a') as f:
            f.write(key_text)
    os.system('chmod 600 -R {}'.format(os.path.expanduser('~/.ssh')))


def init_global():
    """执行全局初始化"""

    # 用环境变量标志是否已经初始化过
    if os.environ.get('_MTCLI_INITED'):
        print("跳过init_sys，因为存在标记")

    os.environ.setdefault('_MTCLI_INITED', 'true')

    if os.environ.get("ID_ED25519", None):
        save_ed25519_private_key(os.environ.get("ID_ED25519"))

    # 如果指定了nottor用户名，则自动创建
    nottor_user_name = os.environ.get('NOTTOR_USER', None)
    if nottor_user_name:
        os.environ['NOTTOR_USER'] = NOTTOR_USER
        try:
            u = pwd.getpwnam(nottor_user_name)
        except KeyError:
            exec(
                """useradd -u 567 -s /bin/bash -m --home-dir /home/{user} -g root {user}"""
                .format(user=NOTTOR_USER))

    if os.environ.get('DISABLE_TOR') == 'true':
        # 禁用tor功能，一般是在调试状态下。
        print(term.format("注意：tor功能已经禁用", term.Color.GREEN), flush=True)
    else:
        os.system('echo "nameserver 127.0.0.1" > /etc/resolv.conf')
        if not tor_helper.ensureIntor():
            print(term.format("tor 启动失败，跳过其他服务的启动", term.Color.RED),
                  flush=True)
            exit(-1)
            return
    print("tor 初始化完成", flush=True)
    # 当前用户名
    user = getpass.getuser()
    os.environ["MT_CLI_USER"] = user
    os.environ["MT_CLI_UID"] = str(pwd.getpwnam(user).pw_uid)
    os.environ["MT_CLI_GID"] = str(pwd.getpwnam(user).pw_gid)
    # 是否处于容器内。
    if os.path.exists('/.dockerenv'):
        os.environ["MTCLI_IS_CONTAINER"] = 'true'


def init_by_env():
    """
        根据环境变量自动启动相关功能
    """

    if not os.environ.get('MT_SSH_DISABLE', False):
        exec('service ssh start')

    # 设置一个root密码。
    os.system('echo "root:{}" | chpasswd'.format(
        os.environ.get('ROOT_PASSWORD', "www.gmail123456.com")))

    # 起始仓库
    if os.environ.get('REPO_RUN', None):
        repo_deploy()


def help(args):
    print("用法")
    parser.print_usage()
    parser.print_help()


def cmd(args):
    exec(args.cmdline)


def install(args):
    """
        执行软件安装，目前主要用户docker 容器环境，
        如果安装文件能独立运行，那么，在docker build 的时候，就可以重复利用缓存。
    """
    package = args.package
    installer = importlib.import_module('mtlibs.installers.' + package)
    installer.install()


def service(args):
    """
        启动自定义服务。
        注意，这些服务名称是本框架所定义的名称
        * 以子进程的方式启动。
        * 对于python脚本，
    """
    services = args.servics
    print(args, flush=True)
    for service in services:
        # 'PYTHONPATH'环境变量表示库路径
        print(service, flush=True)
        os.environ['PYTHONPATH'] = os.environ['APP_ROOT']
        appProcess = subprocess.Popen(
            ['python3', './mtlibs/service/' + service + '.py'], env=os.environ)

    while True:
        time.sleep(1)


def init_args(args):
    """根据启动参数初始化"""
    args.func(args)


def run_args(argv):
    """"""
    print(term.format(
        "================================================= [MTCLI] ====",
        term.Color.GREEN),
          flush=True)
    parser = argparse.ArgumentParser(description="CLI")
    # parser.add_argument('--version', action='store_true', help='show version')
    # sub help
    subparsers = parser.add_subparsers(help='子命令')
    parser_help = subparsers.add_parser('help', help='a help')
    parser_help.set_defaults(func=help)

    # sub exec
    # 用法：entry exec 'whoami && ls /'
    parser_cmd = subparsers.add_parser('cmd', help='执行shell命令')
    parser_cmd.add_argument('cmdline', help='shell 命令')
    parser_cmd.set_defaults(func=cmd)

    # sub install
    # 用法: ./entry install dind
    parser_cmd = subparsers.add_parser('install', help='包安装')
    parser_cmd.add_argument('package', help='包名称')
    parser_cmd.set_defaults(func=install)

    # sub service
    # 用法: ./entry service cliadmin
    parser_cmd = subparsers.add_parser('service', help='启动服务')
    parser_cmd.add_argument('servics', nargs='+', help='服务名称')
    parser_cmd.set_defaults(func=service)

    if (len(sys.argv) < 2):
        args = parser.parse_args(['help'])
    else:
        args = parser.parse_args(sys.argv[1:])

    print(args)
    init_global()
    init_by_env()
    init_args(args)
    args.func(args)