#!/usr/bin/perl

my $DBHOST = "localhost";
my $DBNAME = "temperature";

my $webreport = "http://www.rotary.nu/temp/nattsjo_control/report.php?pw=$password";

my $table =  "nattsjo_relays_cron";
my $crontab_file = "/etc/cron.d/tellstick";


use DBI;
use LWP::Simple;
use strict;


if (exists($ARGV[0])) {
    if (exists($ARGV[3])) {
	my $id= $ARGV[1];
	my $hour= $ARGV[2];
	my $minute= $ARGV[3];

	if ($ARGV[0] eq "update") {
	    my $sql =  "UPDATE $table SET hour = $hour, minute = $minute WHERE id = $id";
	    my $url = $webreport . "&update=$id&hour=$hour&minute=$minute";
	    &do_execute($url, $sql);
	}

	if ($ARGV[0] eq "add") {
            my $sql = "INSERT INTO $table VALUES (null, $id, $hour, $minute)";
            my $url = $webreport . "&add=$id&hour=$hour&minute=$minute";
	    &do_execute($url, $sql);
        }
    }

    if (exists($ARGV[1])) {
        my $id= $ARGV[1];

        if ($ARGV[0] eq "delete") {
	    my $sql = "DELETE FROM $table WHERE id = $id LIMIT 1";
	    my $url = $webreport . "&delete=$id";
	    &do_execute($url, $sql);
	}

	if ($ARGV[0] eq "execute") {
	    my $sql = "SELECT action FROM nattsjo_devices WHERE id = $id";
	    my $db = DBI->connect("DBI:mysql:$DBNAME:$DBHOST", $DBUSER, $DBPASS);
	    $DBI::result = $db->prepare($sql);
	    $DBI::result->execute();
	    my ($cmd, $descr) = $DBI::result->fetchrow_array;
	    print "$descr\n$sql\n\n$cmd\n\n ";
	    print `$cmd` . "\n";
	}
    }
}
&generate_crontab();



sub do_execute() {
    my ($url, $sql) = @_;	
    print "$sql\n\n";
    my $content = get($url);
    print "\n$url\n\n";
    print "$content\n\n";
    my $db = DBI->connect("DBI:mysql:$DBNAME:$DBHOST", $DBUSER, $DBPASS);
    $DBI::result = $db->prepare($sql);
    $DBI::result->execute();
}



sub generate_crontab() {
    open(CRONTAB, ">$crontab_file");
    select CRONTAB;

    print "# Autogenerated crontab for Tellstick\n\n\n";
    my $sql = "SELECT now(), a.action, b.hour, b.minute, a.descr FROM nattsjo_devices a, nattsjo_relays_cron b WHERE b.relay = a.id ORDER BY hour, minute, action";

    my $db = DBI->connect("DBI:mysql:$DBNAME:$DBHOST", $DBUSER, $DBPASS);
    $DBI::result = $db->prepare($sql);
    $DBI::result->execute();
    my $now = "";
    while (my @cron_entries =$DBI::result->fetchrow_array) {
	printf "%02d %2d", $cron_entries[3], $cron_entries[2];
	print " * * * root ";
	print  $cron_entries[1] . " \t# " . $cron_entries[4] . "\n";
	$now = $cron_entries[0];
    }
    print "\n# Generated: $now\n";
}