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


class UpgradeTool():
    '''
    升级工具
    '''

    def load_images(self):
        '''
        加载镜像
        :return:
        '''
        app_name_list = self.get_app_list()
        for app_name in app_name_list:
            if not app_name:
                continue
            image_name = app_name[:-4].replace('___', "/").replace("__", ":")
            print('load docker image:{}'.format(image_name))
            cmd_res = os.system('docker load -i {}'.format(app_name))
            if cmd_res == 1:
                raise RuntimeError('load docker image fail')

    def get_app_list(self):
        '''
        获取app列表
        :return:
        '''
        with os.popen('ls | grep .tar') as f:
            cmd_txt = f.read()

        if not cmd_txt:
            raise RuntimeError('please check files,not find .tar file')

        app_name_list = cmd_txt.split('\n')

        return app_name_list

    def upgrade(self):
        '''
        升级app
        :return:
        '''
        self.load_images()
        print('docker image load complete\n')
        print('start upgrade app\n')
        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('not set app_list in docker-compose.yml')

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

        if app_str == '*':
            res = os.system('''export HUANSI_REGISTRY_URL=47.110.145.204:8084 &&\
source /etc/profile.d/huansi.sh &&\
docker-compose up -d --force-recreate''')
        else:
            res = os.system('''export HUANSI_REGISTRY_URL=47.110.145.204:8084 &&\
source /etc/profile.d/huansi.sh &&\
docker-compose up -d --force-recreate --no-deps {}'''.format(app_str))

        if res == 1: raise RuntimeError('app upgrade fail')

        print('upgrade app complete\n')


if __name__ == "__main__":
    UpgradeTool().upgrade()
