#!/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;

set_known_options( 'low', 'medium', 'high' );

# These values are in BOGOMIPS.  They are arbitrary and will be refined, if possible,
# as more data is collected.  Obviously, BOGOMIPS are not the best CPU benchmarking
# tool.
my $rrd_threshold = 1650; # bogomips at or below this mean rrdtool is too much of a strain
#my $rrd_threshold = 3365;

my $low_threshold = 2500;
my $medium_threshold = 4050;
my $high_threshold = 7400;

# Poll the system to find the CPU type.  Currently, we use bogomips (the bogosity of which
# is in the name itself) to guess how powerful the CPU is.
sub get_CPU_strength {
    my $bogomips=0;
    my @results = split("\n", execute_shell_command("cat /proc/cpuinfo | grep bogomips"));
    foreach my $result (@results) { # Count the bogomips for each core.  Again, this is rough.
	if ($result =~ /bogomips\s*:\s*(\d+.\d+)/) {
	    $bogomips+=$1;
	}
    }
    return $bogomips;
}

# ??? Need to test for storage groups and LVM
# Specific to KnoppMyth
sub get_HDD_size {
    my @HDD_info = split(" +", execute_shell_command("df -h /myth | grep myth"));

    chop($HDD_info[1]);
    return($HDD_info[1] || 0);
}

#sub disable_rrdtool {
#    
#}

# Edit mplayer.conf to tell mplayer to drop video frames when necessary.  This should do no harm
# on systems that don't need the option, and it should make video watchable on those that do.
sub edit_mplayer_conf {
    use vars qw($mplayer_conf);
    $mplayer_conf = "/etc/mplayer/mplayer.conf";

    # delete any old entries that Tweaker made, relevant to this particular edit
    my $delete_old_tweaker_edits = "[ -e $mplayer_conf ] && sed -i '/^.*hardframedrop.*=.*#TWEAKER/d' $mplayer_conf";
    # comment out old entries that some other process may have made
    my $comment_out_external_edits = "[ -e $mplayer_conf ] && sed -i 's/^\\(hardframedrop.*=.*\\)/#\\1/g' $mplayer_conf";
    my $command1;
    my $command2="";
    my $logger = get_logger('tweaker.script');

    if (my $error = execute_shell_command("$delete_old_tweaker_edits && $comment_out_external_edits")) {
	$logger->error("ERROR: $error");
	$logger->error("ERROR: Unable to implement option $option.");
	exit(-1);
    }

    $command2 = "echo -e 'hardframedrop=true #TWEAKER' >> $mplayer_conf";
    if (my $error = execute_shell_command($command2)) {
	$logger->error("ERROR: $error");
	$logger->error("ERROR: Unable to implement option $option.");
	exit(-1);
    }

    $logger->info("Edited $mplayer_conf to drop video frames when CPU is overloaded.");
}

# Try to implement the given option.
sub implement_option {
    my($option) = @_;

    # ??? This will need some work to properly integrate with MythTV 0.21's own CPU-based playback settings.
    # For now, set profile to CPU++ no matter what CPU type, and just change what CPU++ provides.

    $dbconnectionstring = get_mythtv_connection_string();
	
    if (connect_to_db("DBI:mysql:$dbconnectionstring")) {
	switch ($option) {
	    case "low" {
		change_or_make_setting('AutoCommflagWhileRecording', '0') || exit -1;
		change_or_make_setting('Theme', 'Iulius') || exit -1; # Low eye candy, high performance
		#change_or_make_setting('PreferredMPEG2Decoder', 'libmpeg2') || exit -1; # Least CPU usage, lowest quality
		#change_or_make_entry("displayprofiles", [["pref_decoder", "libmpeg2"]], [["profilegroupid", "1"], ["profileid", "1"]]) || exit -1; # Least CPU usage, lowest quality
		change_or_make_setting('DefaultVideoPlaybackProfile', 'CPU--') || exit -1; # best playback defaults for weak hardware
		# Should libmpeg2/ffmpeg be triggered based on CPU type?  libmpeg2 is usually
		# recommended for AMD CPUs.
		# ??? when to use xvmc?

		# Weak CPUs may actually be too weak to run rrdtool without causing problems.
#		if (get_CPU_strength() <= $rrd_threshold) {
#		    disable_rrdtool();
#		}
	    }
	    case "medium" {
		change_or_make_setting('AutoCommflagWhileRecording', '1') || exit -1;
		change_or_make_setting('Theme', 'LinHES') || exit -1; # Moderate eye candy, moderate performance
		#change_or_make_setting('PreferredMPEG2Decoder', 'libmpeg2') || exit -1; # Least CPU usage, lowest quality
		#change_or_make_entry("displayprofiles", [["pref_decoder", "libmpeg2"]], [["profilegroupid", "1"], ["profileid", "1"]]) || exit -1; # Least CPU usage, lowest quality
		change_or_make_setting('DefaultVideoPlaybackProfile', 'CPU+') || exit -1; # best playback defaults for average hardware
		# ??? when to use xvmc?
	    }
	    case "high" {
		change_or_make_setting('AutoCommflagWhileRecording', '1') || exit -1;
		# ??? Interacts with screen aspect ratio
		change_or_make_setting('Theme', 'LinHES') || exit -1; # Moderate eye candy, moderate performance
		#change_or_make_entry("displayprofiles", [["pref_decoder", "ffmpeg"]], [["profilegroupid", "1"], ["profileid", "1"]]) || exit -1; # Most CPU usage, best quality
		#change_or_make_setting('PreferredMPEG2Decoder', 'ffmpeg') || exit -1; # Most CPU usage, best quality
		change_or_make_setting('DefaultVideoPlaybackProfile', 'CPU++') || exit -1; # best playback defaults for powerful hardware
		# ??? when to use xvmc?
	    }
	}
	change_or_make_setting('UseXvMcVld', '0') || exit -1;
	#change_or_make_entry("displayprofiles", [["pref_deint0", "onefield"]], [["profilegroupid", "1"], ["profileid", "1"]]) || exit -1; # Most CPU usage, best quality
	change_or_make_setting('OSDTheme', 'blootube-osd') || exit -1;
	change_or_make_setting('PlayBoxShading', '0') || exit -1;
	change_or_make_setting('PlaybackExitPrompt', '2') || exit -1;
	#edit_mplayer_conf(); # This was found to cause temporary picture freezing when skipping forward through playback, followed by out-of-sync audio and video
    } else {
	exit -1;
    }
    disconnect_from_db();
}

# Try to get a Recommendation Level for $option.
sub poll_options {
    my($option) = @_;

    threshold_test($option, get_CPU_strength(), "CPU", $low_threshold, $medium_threshold, $high_threshold);
}

# Unimplemented in 0.7
sub check_option {
    help;
}

# Unimplemented in 0.7
sub count_iterations {
    help;
}

process_parameters;