#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009 HDE, Inc.
#
# 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; either version 2
# of the License, or (at your option) any later version.
#

import os
import sys
import re
import traceback
import time
import fcntl
import optparse

from installer.const import *
from installer.trans import _, N_
from installer.snack_ui_uninst import SnackUI

env = os._Environ(os.environ)
logfile = env.get("LOGFILE")
config = env.get('KARESANSUI_CONF')

class UninstallError(Exception):
    def __init__(self, value):
        self.value = value
        write_log("%s\n" % value)
    def __str__(self):
        return repr(self.value)

def opt_parser():
    global logfile
    if logfile is None:
        logfile = DEFAULT_UNINSTALL_LOG
    parser = optparse.OptionParser()
    parser.add_option("-l", "--logfile",
                action="store", dest="logfile", default=logfile,
                help=_("Log file location"))
    parser.add_option("-c", "--config",
                action="store", dest="config", default=DEFAULT_KARESANSUI_CONF,
                help=_("Config file location"))
    return parser

def precheck(opts):
    global logfile
    ret = True

    # library check
    if ret is True:
        try:
            import rpm
            import snack
            import socket
            import urllib
        except ImportError, e:
            print >>sys.stderr, _("ERROR: There are not enough libraries. - %s") % ''.join(e.args)
            traceback.format_exc()
            ret = False

    # log file write check
    if ret is True:
        try:
            if os.path.exists(opts.logfile):
                logf = open(opts.logfile, "a")
            else:
                logf = open(opts.logfile, "w")
            logf.close()
            #if opts.logfile[0:5] != "/dev/":
            #    os.unlink(opts.logfile)
        except:
            print >>sys.stderr, _("ERROR: Can't open logfile %s. Please check whether directory have write permission.") % opts.logfile
            traceback.print_exc()
            ret = False

    return ret

def process_uninstall_package(opts,p_callback=None):
    write_log(_("Entering '%s'") % sys._getframe(0).f_code.co_name)

    global logfile
    from installer.utils import execute_command
    from installer.rpmlib import RpmLib

    rpmlib = RpmLib(p_callback)
    rpmlib.doUninstallAll(UNINSTALL_PKGS_REGEX)
    rpmlib.__del__
    del rpmlib

    time.sleep(1)
    write_log(_("Leaving '%s'") % sys._getframe(0).f_code.co_name)
    return True

def process_stop_service(opts,p_callback=None):
    write_log(_("Entering '%s'") % sys._getframe(0).f_code.co_name)

    global logfile
    from installer.utils import run_chkconfig, run_service

    cnt = 0
    if p_callback: p_callback.start(text=_("Disabling services ..."), size=len(REQUIRE_SERVICES)+1)
    if p_callback: p_callback.update(cnt)
    cnt = cnt + 1

    #for _service in REQUIRE_SERVICES:
    for _service in ["hde-libvirtd"]:
        run_chkconfig(_service,"off")
        run_service(_service,"stop")
        if p_callback: p_callback.update(cnt)
        cnt = cnt + 1

    run_chkconfig("libvirtd","on")
    run_service("libvirtd","start")
    if p_callback: p_callback.update(cnt)
    cnt = cnt + 1

    time.sleep(1)
    write_log(_("Leaving '%s'") % sys._getframe(0).f_code.co_name)
    return True

def pre_run(opts, **kwargs):
    p_callback = kwargs.get('progress_callback', None)
    opts.packages = check_package(opts,p_callback)
    return opts

def check_package(opts,p_callback=None):
    from installer.rpmlib import RpmLib

    cnt = 0
    if p_callback: p_callback.start(text=_("Scanning installed packages ..."), size=1)
    if p_callback: p_callback.update(cnt)
    cnt = cnt + 1

    rpmlib = RpmLib(p_callback)
    packages = rpmlib.doQuery(UNINSTALL_PKGS_REGEX)
    rpmlib.__del__
    del rpmlib

    if p_callback: p_callback.update(cnt)
    cnt = cnt + 1

    time.sleep(1)
    return packages


def run(opts, **kwargs):
    p_callback = kwargs.get('progress_callback', None)

    process_stop_service(opts,p_callback)
    process_uninstall_package(opts,p_callback)

    return True

def write_log(message):
    global logfile

    ret = True
    try:
        if os.path.exists(logfile):
            fp = open(logfile,"a")
        else:
            fp = open(logfile,"w")
        fcntl.lockf(fp.fileno(), fcntl.LOCK_EX)
        fp.write("%s\n" % (message))
        fcntl.lockf(fp.fileno(), fcntl.LOCK_UN)
        fp.close()
        os.chmod(logfile, 0600)
    except IOError, e:
        raise "%s" % e
        ret = False
    return ret

def main():
    if os.getuid() != 0:
        print _("ERROR: This program must be executed by super user.")
        sys.exit()

    parser = opt_parser()
    (opts,args) = parser.parse_args()

    if opts.logfile is not None:
        logfile = opts.logfile
    opts.logfile = logfile
    os.environ['LOGFILE'] = opts.logfile

    if config is not None:
        opts.config = config
    os.environ['KARESANSUI_CONF'] = opts.config

    if NEWT_MONO is True:
        os.environ['NEWT_MONO'] = "1"

    """ Pre checker
    """
    if precheck(opts) is False:
        return -1

    """ Start logging
    """
    #if opts.logfile[0:5] != "/dev/" and os.path.exists(opts.logfile):
    #    os.unlink(opts.logfile)

    write_log("""
@====================================================================@
@ %s %s        @
@ %s           Start time: %s  @
@====================================================================@

""" % (TITLE,VERSION,os.path.basename(sys.argv[0]),time.ctime(),))

    """ Run Run Run!!
    """
    return SnackUI(opts).run()

if __name__ == '__main__':
    sys.exit(main())
