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

from util import FileHelper, log


class ImageClass():
    @staticmethod
    def get_app_list_from_compose_file(compose_content):
        '''
        获取app_list
        :param compose_content:
        :return:
        '''
        app_list_str = re.findall('# app_list: ".*"', compose_content)
        if app_list_str:
            app_list_str = app_list_str[0]
        else:
            app_list_str = ""
            print('未设置app_list')

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

    def get_deploy_image(self, compose_path):
        '''
        获取要升级的所有镜像名
        :return:
        '''
        compose_content = FileHelper.get_file_content(compose_path)
        # 获取app_list
        app_list_str = self.get_app_list_from_compose_file(compose_content)
        # 获取要升级的镜镜像名称
        self.deploy_image_list = self._get_deploy_image(app_list_str, compose_content)
        log.info('要升级的镜像信息如下:\n{}'.format(self.deploy_image_list))

    def _get_deploy_image(self, app_list_str, compose_content):
        '''
        获取所有要升级的镜像名
        :param app_list_str:
        :return:
        '''
        # 如果是*，返回所有镜像名
        # 如果是空，跳出
        if app_list_str == "":
            return None
        deploy_image_list = []
        if app_list_str == "*":
            image_list = re.findall(r'image: (.*)\n', compose_content)
            for image in image_list:
                _l = image.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)
                deploy_image_list.append(_image_info)
        else:
            app_list = app_list_str.split(' ')
            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)
                deploy_image_list.append(_image_info)

        return deploy_image_list

    def save_images(self):
        '''
        保存镜像
        :return:
        '''
        if not os.path.exists('/data/upgrade'):
            os.mkdir('/data/upgrade')

        # 删除旧镜像
        os.system('rm -f /data/upgrade/*.tar')

        log.info('开始生成镜像')
        for deploy_image in self.deploy_image_list:
            if not deploy_image:
                continue

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

        log.info('镜像生成完毕,目录为/data/upgrade')
