#!/usr/bin/python

import os
import re
import sys

from optparse import OptionParser

def error(message):
    sys.stderr.write("ERROR: %s\n" % message)
    sys.exit(1)

def check_ati():
    command = "lsmod | grep fglrx"
    fglrx_lines = os.popen(command).readlines()
    if len(fglrx_lines) != 0:
        print "unknown (impossible to determine resolution with fglrx)"
        return True

    return False

def get_resolution():
    command = "xrandr -q"
    xrandr_lines = os.popen(command).readlines()
    star_lines = [l for l in xrandr_lines if "*" in l]
    if len(star_lines) != 1:
        error("%s should return a single line with '*'" % command)

    star_line = star_lines[0]
    match = re.search(r"(\d+)\s?x\s?(\d+)", star_line)
    if not match:
        error("%s should return pixels like '1024 x 768'" % command)

    horizontal = int(match.group(1))
    vertical = int(match.group(2))

    fields = re.split(r"\s+", star_line)
    star_fields = [f for f in fields if "*" in f]
    if len(star_fields) < 1:
        error("%s should return a refresh rate with '*'" % command)

    return (horizontal, vertical)

def check_resolution():
    if check_ati():
        return True

    (horizontal, vertical) = get_resolution()

    print "%d x %d" % (horizontal, vertical)
    return True

def compare_resolution(min_h, min_v):
    if check_ati():
        return True

    (horizontal, vertical) = get_resolution()

    if (horizontal >= min_h) and (vertical >= min_v):
        return True
    else:
        return False

def main(args):
    usage = "Usage: %prog [OPTIONS]"
    parser = OptionParser(usage=usage)
    parser.add_option("--horizontal",
        type="int",
        default=0,
        help="Minimum acceptable horizontal resolution.")
    parser.add_option("--vertical",
        type="int",
        default=0,
        help="Minimum acceptable vertical resolution.")
    (options, args) = parser.parse_args(args)

    if (options.horizontal > 0) and (options.vertical > 0):
        if compare_resolution(options.horizontal, options.vertical):
            return 0
    else:
        if check_resolution():
            return 0

    return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
