import deployables_lib as dl

dl.load_msgs_module("DSP_SHORTNAME-DSP_VERSION", symtab = globals())

dir_moves = [('DSP_SHORTNAME-DSP_VERSION', '') ]

pat = "^\s*\$(?P<key>\S+\w)\s*=\s*(?P<value>['\"].*['\"])\s*;\s*"
sub = "$%(key)s = %(value)s;"
config_file = 'LocalSettings.php'

def install(site, site_conf, instance_conf, msgs):
    # Some checks before install
    actions = ['resolve_location', 'check_disk_quota', 'check_mysql_enabled',
               'check_pass', 'check_install_loc_owner', '']
    # None of above actions requires args
    args_dict = {}
    # Do all actions
    dl.do_install_actions(site, site_conf, instance_conf, msgs,
        globals(), actions, args_dict)

    if msgs.get_severity() != msgs.ERROR:
        actions = ['db_create', 'db_probe', 'archive_unpack', \
                   'exec_php_script', 'handle_security_mode','edit_conf_file', 'access_url']
        install_dir = "/%s" % instance_conf['install_loc'].split('/')[-1:][0]
        conf_vars = [('wgScriptPath', install_dir)]
        args_dict = {
            'archive_unpack': {'dir_moves': dir_moves},
            'exec_php_script' : {
                'script' : 'config/index.php',
                'args' : {
                    'Sitename' : site_conf['siteinfo']['domain'] + ' Wiki',
                    'EmergencyContact' : instance_conf['instance_admin_email'],
                    'LanguageCode' : 'en',
                    'License' : 'no license metadata',
                    'SysopName' : instance_conf['instance_admin'],
                    'SysopPass' : instance_conf['instance_pass1'],
                    'SysopPass2' : instance_conf['instance_pass2'],
                    'DBserver' : dl.get_mysql_host(site),
                    'DBname' : instance_conf['dbname'],
                    'DBuser' : site_conf['mysql']['dbaseadmin'],
                    'DBpassword' : instance_conf['dbpass'],
                    'DBpassword2' : instance_conf['dbpass'] },
                  'success_re' : '.*' },
                'handle_security_mode' : { 'files':[('images', 0777, 0777)]},
                'edit_conf_file': { 'file':'config/' + config_file, 'lang':'php',
                            'pat' : pat, 'sub': sub, 'vars': conf_vars }
            }
        dl.do_install_actions(site, site_conf, instance_conf, msgs,
                              globals(), actions, args_dict)
        fst_path = dl.site_fs(site) + instance_conf['install_loc']
        dl.exec_cmd("mv %s %s" % (fst_path + '/config/' + config_file, \
          fst_path + '/' + config_file))

def reconfigure(context, site, site_conf, old_site_conf, instance_conf,
                old_instance_conf, msgs):

    if context != dl.CONTEXT_SITE_EDIT and dl.mysql_installed(site_conf,
        old_site_conf):

        actions = ['db_probe','handle_url_loc', 'resolve_location',
               'handle_db_changes', 'handle_username_change']

        args_dict = {}

        # We always require the dbpass for mediawiki, since a reconfigure
        # need to peform database updates
        if context != dl.CONTEXT_SITE_EDIT:
           actions.insert(0, 'db_probe')
           args_dict['db_probe'] = {'use_old' : 1}

        dl.do_reconfigure_actions(context, site, site_conf, old_site_conf,
                                  instance_conf, old_instance_conf, msgs,
                                  globals(), actions, args_dict)

        actions = ['archive_unpack']
        args_dict = {'archive_unpack': {'dir_moves': dir_moves } }

        if msgs.get_severity() != msgs.ERROR:
            conf_vars = [('wgDBname', instance_conf['dbname'])]

            if instance_conf['dbname'] != old_instance_conf['dbname']:
                actions += ['edit_conf_file', 'exec_mysql']
                sql_stmt = [ \
                  "UPDATE objectcache SET keyname = '%s:messages' where keyname \
                  = '%s:messages'" % (instance_conf['dbname'], old_instance_conf['dbname']) ]
                args_dict['exec_mysql'] = { 'sql': sql_stmt }
                args_dict['edit_conf_file'] =  {'file': config_file, 'lang': 'php',
                                   'pat': pat, 'sub': sub, 'vars': conf_vars }

            if instance_conf['overwritefiles'] == '1':
               actions.append('handle_security_mode')
               args_dict['handle_security_mode'] = { 'files':[('images', 0777,
                   0777)]}

            dl.do_reconfigure_actions(context, site, site_conf, old_site_conf,
                                  instance_conf, old_instance_conf, msgs,
                                  globals(), actions, args_dict)

def remove(site, site_conf, instance_conf, msgs):
    dl.db_drop(site, site_conf, instance_conf)
    dl.install_loc_cleanup(site, site_conf, instance_conf, dir_moves)

def upgrade(site, site_conf, instance_conf, old_instance_conf, msgs):
    if old_instance_conf['shortname'] == 'mediawiki' and \
       old_instance_conf['version'] == '1.3.9':
        instance_conf['syncfs'] = '1'
        instance_conf['overwritefiles'] = '1'
    
        actions = ['archive_unpack', 'handle_security_mode']
        args_dict = {
            'archive_unpack': {'dir_moves': dir_moves},
            'handle_security_mode' : { 'files':[('images', 0777, 0777)]}
        }
        dl.do_upgrade_actions(site, site_conf, instance_conf, old_instance_conf, \
            msgs, globals(), actions, args_dict)

def get_instance_configuration(context, site, site_conf, instance_conf,
                               old_instance_conf, locale, msgs):
    instance = dl.dsp_create_instance(instance_conf['shortname'],
                                      instance_conf['version'])
    dl.dsp_fill_instance(context, instance, site, site_conf,
                         instance_conf, old_instance_conf,
                         ['dbname', 'username', 'url_net', 'url_path',
                          'domain_to_path', 'instance_admin_email'])
    return instance
