#!/usr/bin/python3
# Copyright (C) 2013 Canonical Ltd.
# Author: Sergio Schvezov <sergio.schvezov@canonical.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json
import os
import os.path
import subprocess

preinstalled_path = '/usr/share/preinstalled/click'
customization_path = '/custom/preinstalled/click'


def install_required(pkg, manifest):
    pkg_manifest = json.loads(
        subprocess.check_output(['click', 'info', pkg]).decode('utf-8'))
    installed_pkg_version = ''
    for item in manifest:
        if item['name'] == pkg_manifest['name']:
            installed_pkg_version = item['version']
            break
    if installed_pkg_version < pkg_manifest['version']:
        return True
    return False


def install():
    install_manifest = subprocess.check_output(
        ['click', 'list', '--manifest'])
    install_manifest = json.loads(install_manifest.decode('utf-8'))

    for click_path in (preinstalled_path, customization_path):
        click_pkg_path = []
        try:
            click_pkg = filter((lambda x: x.endswith('.click')),
                               os.listdir(click_path))
            click_pkg_path = [os.path.join(click_path, x) for x in click_pkg]
        except OSError as e:
            if e.errno == 2:
                print('Directory %s does not exist' % click_path)
                pass
            else:
                raise e
        for pkg in click_pkg_path:
            if install_required(pkg, install_manifest):
                subprocess.call(['/usr/bin/pkcon', 'install-local', pkg])
            else:
                print('Installation of %s not required' % pkg)


def run_required():
    version_file = '/etc/ubuntu-build'
    last_version_run = os.path.expanduser('~/.ubuntu-build')
    if not os.path.exists(version_file):
        print('Not on image based upgrade system, forcing install')
        return True
    with open(version_file, 'r') as f:
        build = f.read().strip()
    if not os.path.exists(last_version_run):
        print('No previous run for %s found, installing' % build)
        with open(last_version_run, 'w') as f:
            f.write(build)
        return True
    with open(last_version_run, 'r') as f:
        last_build = f.read().strip()
    if build == last_build:
        return False
    else:
        print('Previous run was for %s but we are now on %s' %
              (last_version_run, build))
        return True


if __name__ == '__main__':
    if run_required():
        install()
