# -*- coding: utf-8 -*-
#
# «ubi-oem-hooks»
#
# Ubiquity plugin for hook Watauga scripts and copy debconf db.
#
# Copyright (C) 2013, Canonical, Ltd.
#
# Author:
#  - Jian-Ding Chen (timchen119) <tim.chen119@canonical.com>

import os
import sys
import time
import debconf
import syslog

from ubiquity.plugin import *
from ubiquity import install_misc
from ubiquity import misc

NAME = 'ubi-oem-hooks'
AFTER = 'usersetup'
WEIGHT = 12
OEM = True

def print_msg(message):
    time_str = time.ctime()[4:19]
    print('%s %s: %s' % (time_str, NAME, message), file=sys.stderr)

def run_hooks(path, args=[]):
    import subprocess

    if not os.path.exists(path):
        print_msg(path + ' is not exists.')
        return

    command = "run-parts --report " + path
    for arg in args:
        command += " --arg=%s" % arg
    with misc.raised_privileges():
        print_msg('run command: %s' %command)
        proc = subprocess.Popen(command,
                                stdout = subprocess.PIPE,
                                stderr = subprocess.STDOUT,
                                universal_newlines=True,
                                shell=True)
        stdout, _ = proc.communicate()
        with open('/var/log/installer/ubiquity-oem-hooks.log', 'a') as log:
            log.write(stdout)
        log.close()
    return

class Install(InstallPlugin):
    def __init__(self, frontend, db=None, ui=None):
        # Check for hook
        self.ubiquity_hooks = '/usr/share/ubuntu/scripts/ubiquity.d/custom'
        try:
            if db: self.ubiquity_hooks = db.get('ubiquity/custom_commands')
        except debconf.DebconfError as err:
            print_msg(str(err))

        self.oobe_hooks = '/usr/share/ubuntu/scripts/oem-config.d/custom'
        try:
            if db: self.oobe_hooks = db.get('oem-config/custom_commands')
        except debconf.DebconfError as err:
            print_msg(str(err))

        # Parameter init
        InstallPlugin.__init__(self, frontend, db, ui)

    def install(self, target, progress, *args, **kwargs):
        if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
            run_hooks(self.oobe_hooks, args=['oem-config'])
            return

        try:
            extras = progress.get('apt-setup/extras')
            if extras:
                install_misc.set_debconf(target, 'apt-setup/extras', extras, progress)
            partner = progress.get('apt-setup/partner')
            if partner:
                install_misc.set_debconf(target, 'apt-setup/partner', partner, progress)
            security_host = progress.get('apt-setup/security_host')
            if security_host:
                install_misc.set_debconf(target, 'apt-setup/security_host', security_host, progress)
            bypass_ttf_hanyi = progress.get('locale-support-plugin/bypass-ttf-hanyi')
            if bypass_ttf_hanyi:
                install_misc.set_debconf(target, 'locale-support-plugin/bypass-ttf-hanyi', bypass_ttf_hanyi, progress)
        except debconf.DebconfError as err:
            print_msg(str(err))

        # Run ubiquity custom hooks
        run_hooks(self.ubiquity_hooks, args=['ubiquity'])
