# -*- coding:utf-8 -*-
import json
import os
import re

'''
代理要配置四处
linux  全局代理
docker Service的代理
docker 容器的代理
runner 内部的git代理
'''


def set_docker_service_proxy(ip_and_port):
    '''
    docker Service的代理
    :param ip_and_port:
    :return:
    '''
    if ip_and_port is None:
        return

    docker_service_path = '/usr/lib/systemd/system/docker.service'

    # docker Service的代理
    with open(docker_service_path, 'r') as f:
        content = f.read()

    if 'Environment="HTTP_PROXY=http://' not in content:
        content = content.replace('[Service]', '[Service]\nEnvironment="HTTP_PROXY=http://{}"'.format(ip_and_port))
    else:
        pattern = re.compile(r'(Environment="HTTP_PROXY=http://\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:\d{1,5}\")')
        r_str = '''Environment="HTTP_PROXY=http://{}"'''.format(ip_and_port)
        content = re.sub(pattern, r_str, content)

    # 重新写入
    with open(docker_service_path, 'w') as f:
        f.write(content)

    # 重启docker
    s = os.system("systemctl daemon-reload && sudo systemctl restart docker")
    if s == 0:
        print("docker Service的代理配置成功")
    else:
        print("docker Service的代理配置失败")


def set_linux_global_proxy(ip_and_port):
    '''
    linux全局代理
    :param ip_and_port:
    :return:
    '''
    if ip_and_port is None:
        return

    proxy_sh_path = '/etc/profile.d/proxy.sh'

    with open(proxy_sh_path, 'w') as f:
        f.write("export http_proxy=http://{}".format(ip_and_port))

    s = os.system("source {}".format(proxy_sh_path))
    if s == 0:
        print("linux全局代理配置成功")
    else:
        print("linux全局代理配置失败")


def set_docekr_container_proxy(ip_and_port):
    '''
    docker 容器的代理
    :param ip_and_port:
    :return:
    '''
    if ip_and_port is None:
        return

    docker_config_path = '/root/.docker/config.json'

    if not os.path.exists(docker_config_path):
        os.mkdir('/root/.docker')
        with open(docker_config_path, 'w') as f:
            c_dit = {}
            c_dit['proxies'] = {"default": {"httpProxy": "http://{}".format(ip_and_port)}}
            c_str = json.dumps(c_dit, indent=4)
            f.write(c_str)
    else:
        with open(docker_config_path, 'r') as f:
            content = f.read()

        c_dit = json.loads(content)
        if c_dit.get('proxies') is None:
            c_dit['proxies'] = {"default": {"httpProxy": "http://{}".format(ip_and_port)}}
        else:
            c_dit['proxies']['default']['httpProxy'] = "http://{}".format(ip_and_port)

        c_str = json.dumps(c_dit, indent=4)

        with open(docker_config_path, 'w') as f:
            f.write(c_str)

    print('docker 容器的代理配置成功')


def set_gitlab_runner_git_proxy(ip_and_port):
    '''
    runner 内部的git代理
    :param ip_and_port:
    :return:
    '''
    if ip_and_port is None:
        return

    gitlab_runner_config_path = '/etc/gitlab-runner/config.toml'

    if not os.path.exists(gitlab_runner_config_path):
        raise RuntimeError('请先配置gitlab-runner再来执行代理脚本')

    with open(gitlab_runner_config_path, 'r') as f:
        content = f.read()

    if "environment = [\"http_proxy=" in content:
        pattern = re.compile(
            r'(\[\"http_proxy=http://\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:\d{1,5}\", \"HTTP_PROXY=\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:\d{1,5}\"\])')
        r_str = '''["http_proxy=http://{0}", "HTTP_PROXY={0}"]'''.format(ip_and_port)
        content = re.sub(pattern, r_str, content)
    else:
        r_str = '''executor = "docker"
  pre_clone_script = "git config --global http.proxy $HTTP_PROXY"
  environment = ["http_proxy=http://{0}", "HTTP_PROXY={0}"]
  [runners.custom_build_dir]'''.format(ip_and_port)

        content = content.replace('executor = "docker"\n  [runners.custom_build_dir]', r_str)

    with open(gitlab_runner_config_path, 'w') as f:
        f.write(content)

    print('gitlab-runner 内部git代理配置成功')


if __name__ == '__main__':
    ip_and_port = input("请输入代理的ip地址和端口(列如192.168.1.1:808):").strip()

    # CCProxy代理默认端口808
    if ":" not in ip_and_port:
        ip_and_port = ip_and_port + ":808"

    set_gitlab_runner_git_proxy(ip_and_port)
    set_linux_global_proxy(ip_and_port)
    set_docker_service_proxy(ip_and_port)
    set_docekr_container_proxy(ip_and_port)