#!/usr/bin/perl -w

# Copyright 2007-2009 Robert ("Bob") Igo of StormLogic, LLC and mythic.tv.
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use Switch;
use Tweaker::Script;
package Tweaker::Script;

# List all the options that this script supports.  Make sure it matches what's in
# the corresponding .tcf entry.
set_known_options( 'low', 'medium', 'high' );

sub check_for_GL() {
    # ??? Need to make this update a class variable instead of a temp file.
    my $fps = execute_shell_command("[ -e /tmp/fps ] && cat /tmp/fps") || -1;

    # We think that any nVidia cards at or below NV25 are not well-supported
    # for GL.  Newer cards are NV34 or above, or have a different starting letter.
    my $generation = execute_shell_command("lspci -v | grep \"nVidia Corporation\" | grep VGA | awk -FCorporation '{ print \$2 }' | awk '{ print \$1 }'");
    my $letters = substr($generation,0,2);
    if (("$letters" eq "NV") && ("$generation" lt "NV24")) {
	$fps = 0;
    }
    
    if ($fps == -1) {
	my $result = execute_shell_command("glxinfo | grep 'direct rendering'");
	if ($result =~ m/direct rendering: Yes/) {
	    my $logger = get_logger('tweaker.script');
	    $logger->info("Hardware OpenGL rendering ability detected.");
	    # Now poll the strength, returning the FPS from glxgears, run at the default resolution.
	    # I would love to be able to poll this in a way that 1) doesn't pop up a GUI window and
	    # 2) doesn't rely on manually making a database that maps video cards to performance levels.
	    $result = execute_shell_command("script -q -c \"glxgears -fullscreen &  sleep 11 ;  pkill -15 glxgears\" | grep FPS | tail -1");
	    if ($result =~ m/ (\d+)\.\d+ FPS/) {
		$fps = $1;
		execute_shell_command("echo $fps > /tmp/fps");
	    }
	} else {
	    $fps = 0;
	    execute_shell_command("echo $fps > /tmp/fps");
	}
    }
    return $fps;
}

# Try to implement the given option.
sub implement_option {
    my($option) = @_;
    
    $dbconnectionstring = get_mythtv_connection_string();
	
    if (connect_to_db("DBI:mysql:$dbconnectionstring")) {
	switch ($option) {
	    # List all the options that this script supports.  You can have as many as you like.
	    case "low" {
		change_or_make_setting('ThemePainter', 'Qt') || exit -1;
		change_or_make_setting('SlideshowUseOpenGL', '0') || exit -1;
		change_or_make_setting('SlideshowOpenGLTransition', 'none') || exit -1;
		change_or_make_setting('SlideshowTransition', 'none') || exit -1;
	    }
	    case "medium" {
		change_or_make_setting('ThemePainter', 'Qt') || exit -1;
		change_or_make_setting('SlideshowUseOpenGL', '1') || exit -1;
		change_or_make_setting('SlideshowOpenGLTransition', 'random (gl)') || exit -1;
		change_or_make_setting('SlideshowTransition', 'random') || exit -1;
	    }
	    case "high" {
		change_or_make_setting('ThemePainter', 'opengl') || exit -1;
		change_or_make_setting('SlideshowUseOpenGL', '1') || exit -1;
		change_or_make_setting('SlideshowOpenGLTransition', 'random (gl)') || exit -1;
		change_or_make_setting('SlideshowTransition', 'random') || exit -1;
	    }

	    # In all cases, do the following:

	    # enable anti-aliased fonts
	    my $qtrc="/home/mythtv/.qt/qtrc";
	    # clean out old Xft settings
	    my $command = "sed -i 's/.*Xft=.*//g' $qtrc";

	    if (my $error = execute_shell_command($command)) {
		my $logger = get_logger('tweaker.script');
		$logger->error("ERROR: $error");
		$logger->error("ERROR: Unable to implement option $option.");
		exit(-1);
	    } else {
		# Add Xft settings
		my $command = "sed -i 's/embedFonts=true/embedFonts=true\nenableXft=true\nuseXft=true/g' $qtrc";
		if  (my $error = execute_shell_command($command)) {
		    my $logger = get_logger('tweaker.script');
		    $logger->error("ERROR: $error");
		    $logger->error("ERROR: Unable to implement option $option.");
		    exit(-1);
		} else {
		    # Make sure to use an AA-capable font
		    my $command = "sed -i 's/font=.*/font=Sans Serif,12,-1,5,50,0,0,0,0,0/g' $qtrc";
		    if  (my $error = execute_shell_command($command)) {
			my $logger = get_logger('tweaker.script');
			$logger->error("ERROR: $error");
			$logger->error("ERROR: Unable to implement option $option.");
			exit(-1);
		    }
		}
	    }
	}
    } else {
	exit -1;
    }
    disconnect_from_db();
}

# Poll the system to see what recommendationlevel the given option has on the system.
sub poll_options {
    my($option) = @_;
    
    # These are somewhat arbitrary at this point.  Note that they correspond to
    # _full screen_ glxgears results in Frames Per Second (FPS), since GL is used
    # at full screen resolution in MythTV.
    my $low_threshold = 350; # at or below $low_threshold FPS, GL is not considered good enough to use in MythTV
    my $medium_threshold = 425; # GL is pretty usable here
    my $high_threshold = 500;

    threshold_test($option, check_for_GL(), "video card", $low_threshold, $medium_threshold, $high_threshold);
}

# Unimplemented in 0.7
sub check_option {
    help;
}

# Unimplemented in 0.7
sub count_iterations {
    help;
}

process_parameters;