#!/usr/bin/python
#
# Copyright (c) 2008 Grigori Goronzy <greg@geekmind.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

import dbus
import dbus.mainloop.glib
import dbus.glib
import gobject
import os, sys, commands, glob
import __builtin__
import EeeControl.daemonize
import EeeControl.actions
import EeeControl.models

PIDFILE = "/var/run/eee-control-daemon.pid"

if __name__ == "__main__":
    # Sanity checks
    if os.geteuid() != 0:
        print "I can only run as root."
        sys.exit(1)

    if not (os.path.exists("/proc/acpi/asus") or os.path.exists("/sys/devices/platform/eeepc")):
        print "Cannot access ACPI control files!"
        print "Make sure the modules eeepc_acpi (or eeepc_laptop) are loaded."
        sys.exit(1)

    if os.path.exists("/proc/eee"):
        print "The asus_eee module is loaded.  This conflicts with eee-control. Please unload the module and try again."
        sys.exit(1) 

    # Check if we are running on a supported Eee PC model
    manu = open("/sys/class/dmi/id/sys_vendor").readline().strip()
    model = open("/sys/class/dmi/id/product_name").readline().strip()
    if not manu.startswith("ASUS") or not model in EeeControl.models.MODEL_MAP.keys():
        print "You are not using a supported Eee PC model. Continuing anyway with autodetection."
        model = "AUTODETECT"
        
    # Initialize logger
    def _log(text, level=3, module=None):
        if __builtin__._loglevel >= level:
            if module: print "%s: %s" %(module, text)
            else: print text
    __builtin__.log = _log
    
    # Use the option -V to disable daemonization
    __builtin__._loglevel = 0
    if len(sys.argv) > 1 and sys.argv[1] == "-V": __builtin__._loglevel = 3
    else:
        # Daemonize
        EeeControl.daemonize.become_daemon(our_home_dir="/")
        # Create a PID file
        f = open(PIDFILE, "w")
        f.write(str(os.getpid()))
        f.close()
    
    # Set up DBus
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    bus = dbus.SystemBus()
    name = dbus.service.BusName("org.eee.Eee", bus)
    
    # Determine ACPI base
    if os.path.exists("/proc/acpi/asus"):
        acpi_base = "/proc/acpi/asus"
        hwkey_control = True
    else:
        acpi_base = "/sys/devices/platform/eeepc"
        hwkey_control = False

    if os.path.exists(os.path.join(acpi_base, "brn")):
        brn_path = os.path.join(acpi_base, "brn")
    elif os.path.exists("/sys/class/backlight/acpi_video0/brightness"):
        brn_path = "/sys/class/backlight/acpi_video0/brightness"
    elif os.path.exists("/sys/class/backlight/psblvds/brightness"):
        brn_path = "/sys/class/backlight/psblvds/brightness"
    elif os.path.exists("/sys/class/backlight/eeepc/brightness"):
        brn_path = "/sys/class/backlight/eeepc/brightness"
    else:
        brn_path = "/dev/null"

    if os.path.exists(os.path.join(acpi_base, "bt")):
        bt_path = os.path.join(acpi_base, "bt")
    else:
        bt_path = None

    if os.path.exists(os.path.join(acpi_base, "wlan")):
        wlan_path = os.path.join(acpi_base, "wlan")
    else:
        wlan_path = "/dev/null"

    # Linux 2.6.27 uses rfkill interface for toggling wifi or
    # bluetooth. If either /sys/class/rfkill/*/type == "bluetooth" or
    # "wifi", use it instead of the acpi_base file
    rfkill_base = "/sys/class/rfkill/"
    for p in glob.glob(os.path.join(rfkill_base, "*")):
        log("rfkill: testing %s" %p)
        rfkill_type = os.path.join(p, "type")
        rfkill_state = os.path.join(p, "state")
        if os.path.exists(rfkill_type):
            f = open(rfkill_type)
            l = f.readline()
            type = l.strip()
            f.close()
            if type == "bluetooth":
                log("rfkill: found bluetooth")
                bt_path = rfkill_state
            if type == "wlan":
                log("rfkill: found wifi")
                wlan_path = rfkill_state
                # If rfkill is identified as managing wlan state, do not
                # much with the interface device or the module
                wlan_rfkill = True

    # Add DBus object for the Eee PC
    eee_model = EeeControl.actions.EeeActions(bus, manu, model, acpi_base, brn_path, bt_path, wlan_path, hwkey_control)
    EeeControl.actions.AcpiParser(eee_model)
    
    # GO!
    ml = gobject.MainLoop()
    ml.run()
