# -*- coding:utf-8 -*-


'''
在upgrade_app写入需要升级的镜像,回车隔开,格式为 镜像名:版本号
'''

import os
import re

if __name__ == '__main__':
    with open('docker-compose.yml', 'r') as f:
        compose_content = f.read()

    app_list_str = re.findall('# app_list: ".*"', compose_content)
    if app_list_str:
        app_list_str = app_list_str[0]
    else:
        raise RuntimeError('未设置app_list')

    app_str = app_list_str[len('# app_list: "'):-1]

    app_list = app_str.split(' ')

    if not os.path.exists('/data/upgrade'):
        os.mkdir('/data/upgrade')

    image_list = []
    if app_str == '*':
        app_list = re.findall(r'image: (.*)\n', compose_content)
        for app in app_list:
            _l = app.split(':')
            if len(_l) == 1:
                tag = 'latest'
            else:
                tag = _l[1]
            _image_info = '{}:{}'.format(_l[0].replace('${HUANSI_REGISTRY_URL}', '47.110.145.204:8084'), tag)
            image_list.append(_image_info)
    else:
        for app in app_list:
            image_info = re.findall(r'{}:(.*)\n(.*)image: (.*)\n'.format(app), compose_content)[0][-1:][0]
            _l = image_info.split(':')
            if len(_l) == 1:
                tag = 'latest'
            else:
                tag = _l[1]
            _image_info = '{}:{}'.format(_l[0].replace('${HUANSI_REGISTRY_URL}', '47.110.145.204:8084'), tag)
            image_list.append(_image_info)

    print('开始生成镜像')
    for image in image_list:
        if not image:
            continue

        print('        生成镜像:{}'.format(image))
        file_name = image.replace('/', '___').replace(':', '__') + '.tar'
        _cmd = 'docker save {} -o /data/upgrade/{}'.format(image, file_name)
        result = os.system(_cmd)
        if result == 1:
            raise RuntimeError("{}执行出错".format(_cmd))

    print('镜像生成完毕')

    os.system('mv ./docker-compose.yml /data/upgrade/docker-compose.yml')
