# coding=utf-8
import os


def install_runner(HSCUSCODE=None):
    # 创建配置文件
    if not HSCUSCODE:
        HSCUSCODE = input("请输入客户代号HSCUSCODE:")
        print(HSCUSCODE)

    os.system("rm /etc/gitlab-runner/config.toml -f && sudo docker stop gitlab-runner && docker rm gitlab-runner")
    register_huansi_runner(HSCUSCODE)

    os.system("sudo chmod 777 /etc/gitlab-runner/config.toml")
    with open('/etc/gitlab-runner/config.toml', 'r') as f:
        s = f.read()
        a = s.replace(' volumes = ["/cache"]',
                      'volumes = ["/var/run/docker.sock:/var/run/docker.sock","/etc/profile.d/huansi.sh:/etc/profile.d/huansi.sh" ,"/cache","/huansi/gitlab-runner/builds:/builds/hs"]')
    with open('/etc/gitlab-runner/config.toml', 'w') as f:
        f.write(a)

    s2 = os.system("sudo docker run -d --name gitlab-runner --restart always \
                   -v /etc/gitlab-runner:/etc/gitlab-runner \
                   -v /var/run/docker.sock:/var/run/docker.sock \
                   -v /etc/profile.d/huansi.sh:/etc/profile.d/huansi.sh \
                   47.110.145.204:8084/huansi/gitlab-runner:latest")
    assert s2 == 0, "安装runner失败"

    s3 = os.system("sudo docker restart gitlab-runner")
    assert s3 == 0, "runner 配置成功"


def register_gitlab_runner(HSCUSCODE):
    s4 = os.system("sudo docker run --rm -t -i -v /etc/gitlab-runner:/etc/gitlab-runner 47.110.145.204:8084/huansi/gitlab-runner register \
                       -n -u https://gitlab.com/ -r Y1Px-4YpZ8qevi6vCxVY --executor docker --docker-image docker \
                       --description gitlab.{hscode} \
                       --tag-list {hscode}".format(hscode=HSCUSCODE))
    assert s4 == 0, "gitlab_runner配置失败,如果要重新执行,不要再次执行init.py文件,请直接执行install_docker.py文件"


def register_huansi_runner(HSCUSCODE):
    s1 = os.system("sudo docker run --rm -t -i -v /etc/gitlab-runner:/etc/gitlab-runner 47.110.145.204:8084/huansi/gitlab-runner register \
                       -n -u http://47.110.145.204:8085/ -r WwpzH4qk19KjvAjEwoTz --executor docker --docker-image docker \
                       --description huansi.{hscode} \
                       --tag-list huansi.{hscode}".format(hscode=HSCUSCODE))
    assert s1 == 0, "huansi_runner配置失败,如果要重新执行,不要再次执行init.py文件,请直接执行install_docker.py文件"


if __name__ == '__main__':
    if os.path.exists('/etc/gitlab-runner'):
        install_runner()
        print("runner安装成功")
