#!/usr/bin/perl
#
# Copyright 2001-2005 Daniel Klein, dan@klein.com.  All Rights Reserved.
#
# This program will read a version 1.x thermd.conf file (from
# /etc/thermd.conf or the argument) and write a new version to STDOUT
#

my $config_file = shift || "/etc/thermd.conf";

use constant DESC	=> 0;
use constant ADJUST	=> 1;
use constant MIN	=> 2;
use constant MAX	=> 3;
use constant EMAIL	=> 4;

my ($line, $desc);
open CONF, $config_file	or die "Cannot read configuration file $config_file.\n";
while (<CONF>) {
    chomp;
    s/#.*//;
    next if /^\s*$/;
    if (s/\\$//) {		# Handle continued lines
	my $continuation = <CONF>;
	$continuation =~ s/^\s+//;
	$_ .= $continuation;
	redo;
	}
    ($line, $desc) = /^(\d)\s+(.*)/;
    warn "*** Bad config line $, in $config_file\n"
	unless defined $line && $desc;
    $conf[$line] = [ split /\|/, $desc ];
    warn "*** Missing alarm email in $config_file for $conf[$line]->[DESC]\n"
	if $line != 0 && @{$conf[$line]} > 2 && @{$conf[$line]} < 5;
    }
$conf[0] ||= ["F", "F", "Undisclosed location"];
close CONF;



print "DisplayIn\t$conf[0][1]\n";
print "Location\t$conf[0][2]\n"		if $conf[0][2];
print "GPSCoordinates\t$conf[0][3]\n"	if $conf[0][3];
print "MapURL\t\t$conf[0][4]\n"		if $conf[0][4];
print "\n";

print "<Collector Converted>\n    Type\tQK145\n    Scale\t$conf[0][0]\n";

for $x (1..4) {
    next unless $conf[$x];
    print "    <Sensor $x>\n";
    print "\tName\t$conf[$x][0]\n";
    print "\tAdjustBy\t$conf[$x][1]\n"	if $conf[$x][1];
    if ($conf[$x][2]) {
	print "\t<Alarm low>\n\t    Below\t$conf[$x][2]\n";
	for (split /,/, $conf[$x][4]) {
	    print "\t    Notify\t$_\n";
	    }
	print "\t</Alarm>\n";
	}
    if ($conf[$x][3]) {
	print "\t<Alarm high>\n\t    Above\t$conf[$x][3]\n";
	for (split /,/, $conf[$x][4]) {
	    print "\t    Notify\t$_\n";
	    }
	print "\t</Alarm>\n";
	}
    print "    </Sensor>\n";
    }
print "</Collector>\n";
