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

import os
import subprocess

from . import crypto
from .imagebuilder import ImageNotFoundError
from .packer import Packer
from .paths import REPO_APPS_DIR

class AppPacker(Packer):
    def __init__(self, app):
        super().__init__()
        self.app = app
        # Prepare package file names
        self.tar_path = os.path.join(REPO_APPS_DIR, '{}.tar'.format(self.app.name))
        self.xz_path = '{}.xz'.format(self.tar_path)

    def pack(self):
        # Check if all images used by containers exist
        for container in self.app.conf['containers']:
            image = self.app.conf['containers'][container]['image']
            if image not in self.packages['images']:
                raise ImageNotFoundError(image)
        try:
            os.unlink(self.xz_path)
        except FileNotFoundError:
            pass
        self.create_archive()
        self.register()
        self.sign_packages()

    def remove(self):
        self.unregister()
        try:
            os.unlink(self.xz_path)
        except FileNotFoundError:
            pass

    def create_archive(self):
        # Create archive with application setup scripts
        print('Archiving setup scripts for', self.app.name)
        scripts = ('install', 'install.sh', 'upgrade', 'upgrade.sh', 'uninstall', 'uninstall.sh')
        scripts = [s for s in scripts if os.path.exists(os.path.join(self.app.build_dir, s))]
        subprocess.run(['tar', '--xattrs', '-cpf', self.tar_path, '--transform', 's,^,{}/,'.format(self.app.name)] + scripts, cwd=self.app.build_dir)
        self.compress_archive()

    def register(self):
        # Register package in global repository metadata file
        print('Registering application package', self.app.name)
        self.packages['apps'][self.app.name] = self.app.conf.copy()
        self.packages['apps'][self.app.name]['size'] = self.tar_size
        self.packages['apps'][self.app.name]['pkgsize'] = self.xz_size
        self.packages['apps'][self.app.name]['sha512'] = crypto.hash_file(self.xz_path)
        self.save_repo_meta()

    def unregister(self):
        # Removes package from global repository metadata file
        if self.app.name in self.packages['apps']:
            del self.packages['apps'][self.app.name]
            self.save_repo_meta()