#!/usr/bin/python

# Brightness changer script for Linux systems that don't really support brightness.
# Created by Oleh 'BlaXpirit' Prypin.

# Tested with Python 2.7 and 3.2, but Python 3 is recommended.

usage="""
brightness
    - get current brightness setting

brightness restore
    - set the brightness to the last used value

brightness <value>
    - set the brightness to *value*

brightness inc [step]
brightness dec [step]
    - increase or decrease the brightness by *step* (if it's not specified, a default value is used from the configuration file, usually 10% of maximal brightness)
"""

config_file='/etc/bx_brightness.conf'

########################################

import sys,os,collections,subprocess

def find_backlight_device():
    path='/sys/class/backlight/'
    try:
        return os.path.join(path,os.listdir(path)[0])
    except:
        print('No backlight device found!')
        exit(2)

# Settings: (name,(type,default))
s=collections.OrderedDict((
    ('device_path'   ,(str,find_backlight_device)),
    ('min_brightness',(int,lambda:0)),
    ('max_brightness',(int,lambda:int(open(os.path.join(s['device_path'],'max_brightness')).read()))),
    ('step'          ,(int,lambda:max(1,(s['max_brightness']-s['min_brightness'])//10))),
    ('brightness'    ,(int,lambda:int(open(os.path.join(s['device_path'],'brightness')).read()))),
))

# Read settings from config file
try:
    for l in open(config_file).read().split('\n'):
        l=l.split('=',1)
        if len(l)==2 and l[0] in s:
            s[l[0]]=s[l[0]][0](l[1])
except:
    pass

# Replace the settings that couldn't be read with defaults
for k,v in s.items():
    if isinstance(v,tuple):
        s[k]=v[1]()


# Makes the number *v* be in range [*minv*, *maxv*]
def btw(minv,v,maxv):
    if v<minv: v=minv
    if v>maxv: v=maxv
    return v
# Sets the brightess setting and writes it to the 'brightness' file
def set_brightness(b):
    s['brightness']=btw(s['min_brightness'],b,s['max_brightness'])
    with open(os.path.join(s['device_path'],'brightness'),'w') as f:
        f.write(str(s['brightness']))

p=sys.argv[1:]
# brightness
if len(p)==0:
    print('{}/{}'.format(s['brightness'],s['max_brightness']))
    exit(0)
# brightness restore
elif len(p)==1 and p[0]=='restore':
    subprocess.call(['chmod','666',os.path.join(s['device_path'],'brightness')])
    set_brightness(s['brightness'])
# brightness <value>
elif len(p)==1 and p[0].isdigit():
    set_brightness(int(p[0]))
# brightness inc [step]
# brightness dec [step]
elif p[0] in ('inc','dec'):
    try:
        step=int(p[1])
    except:
        step=s['step']
    set_brightness(s['brightness']+step*(1 if p[0]=='inc' else -1))
else:
    print(usage)
    exit(1)


# Save settings
e=os.path.exists(config_file)
with open(config_file,'w') as f:
    f.write('\n'.join('{}={}'.format(*i) for i in s.items()))
if not e: subprocess.call(['chmod','666',config_file])