#!/usr/bin/tclsh8.5
#
# $Id: efef64b5fca1651e1c504c6221fd2c109c98ed45 $
#

## The common defaults
set filters_init_file "/usr/local/libexec/nbsp/filters.init";
if {[file exists $filters_init_file] == 0} {
    puts "uafilter disabled: $filters_init_file not found.";
    return 1;
}
source $filters_init_file;
unset filters_init_file;

if {$filters_init_status == 1} {
    return 1;
}
unset filters_init_status;

# packages
package require nbsp::util;

set ua_init_file [file join $common(libdir) "uafilter.init"];
if {[file exists $ua_init_file] == 0} {
    log_msg "uafilter disabled: $ua_init_file not found.";
    return 1;
}
source $ua_init_file;
unset ua_init_file;

#
# Functions
#
proc main {argc argv} {

    global uafilter;
    global errorInfo;

    # The upperair data directory must exist
    if {[file isdirectory $uafilter(datadir)] == 0} {
	log_msg "$uafilter(datadir) does not exist.";
	return 1;
    }

    cd $uafilter(datadir);
	
    # gets returns -1 on eof. In addition the server explicitly
    # signals the filters to quit by sending a blankline
    # (gets returns 0 in this case, and finfo is "").

    while {[gets stdin finfo] >= 0} {
	if {$finfo == ""} {
	    log_msg "Received request to quit.";
	    break;
	}

	set status [catch {process $finfo} errmsg];
	if {$status == 1} {
	    log_msg "Error processing $finfo";
	    log_msg $errmsg;
	    log_msg $errorInfo;
	}
    }
}

proc process {finfo} {

    global uafilter;

    filterlib_get_rcvars rc $finfo -nobody;

    if {[regexp $uafilter(regex) $rc(fname)] == 0} {
	return;
    }

    set status [catch {
        save_data rc;
    } errmsg];

    if {$status != 0} {
	log_msg $errmsg;
    }
}

proc save_data {rc_name} {

    upvar $rc_name rc;
    global uafilter;

    set fpath $rc(fpath);
    set wmotime $rc(wmotime);

    set rawdata [exec nbspfm35d -s $uafilter(FS) $fpath];
    set dcdata [exec nbspfm35d -d -s $uafilter(FS) $fpath];

    if {$rawdata eq ""} {
	# nbspfm35d returns an empty string if the file does not contain
	# a valid report.
	return;
    }

    save_csv $wmotime $dcdata;

    # Extract the data and save it in the daily/hourly archives.
    if {$uafilter(fm35_daily_enable) == 1} {
	save_fm35_daily $wmotime $rawdata;
    }

    if {$uafilter(fm35_hourly_enable) == 1} {
	save_fm35_hourly $wmotime $rawdata;
    }

    # Call the post (user) filter if it is has been defined.
    if {[file executable $uafilter(postfilter)]} {
	set status [catch {
	    set F [open "|$uafilter(postfilter)" w];
	    puts $F $rawdata;
	} errmsg];

	if {[info exists F]} {
	    close $F;
	}

	if {$status != 0} {
	    log_msg $errmsg;
	}
    }
}

proc save_csv {wmotime dcdata} {

    global uafilter;

    set seconds [::nbsp::util::date::clock_seconds $wmotime];
    set ymd [clock format $seconds -gmt true -format "%Y%m%d"];

    set dcdata_list [split $dcdata "\n"];

    # Each member of the list is of the form
    # <wmostation>,<wmotime>,<stnumber>,<obtime> <leveldata>

    foreach data $dcdata_list {
	set info [lindex [split $data] 0];
        set station [lindex [split $info $uafilter(FS)] end-1];
	set arcvfname ${station}_${ymd};
	append arcvfname $uafilter(csv_fext);

	set savesubdir [file join $uafilter(csv_dir) $ymd];
	file mkdir $savesubdir;
	set arcvfile [file join $savesubdir $arcvfname];
	set csvoutput [exec nbspuatocsv -i $data -s $uafilter(FS)];
	filterlib_file_append $arcvfile $csvoutput;
    }
}

proc save_fm35_daily {wmotime rawdata} {

    global uafilter;

    set seconds [::nbsp::util::date::clock_seconds $wmotime];
    set ymd [clock format $seconds -gmt true -format "%Y%m%d"];

    set rawdata_list [split $rawdata "\n"];
    foreach data $rawdata_list {
  	set data_parts [split $data $uafilter(FS)];
        set station [lindex $data_parts 2];
	set arcvfname ${station}_${ymd};
	append arcvfname $uafilter(fm35_fext);

	# The wsfilter (uatomdf) depdens on this structure
	set savesubdir [file join $uafilter(fm35_dir) $ymd \
	    $uafilter(fm35_daily_subdir)];
	file mkdir $savesubdir;

	set arcvfile [file join $savesubdir $arcvfname];
	filterlib_file_append $arcvfile $data;
    }
}

proc save_fm35_hourly {wmotime rawdata} {

    global uafilter;

    set seconds [::nbsp::util::date::clock_seconds $wmotime];
    set ymd [clock format $seconds -gmt true -format "%Y%m%d"];
    set ymdh [clock format $seconds -gmt true -format "%Y%m%d%H"];
  
    set arcvfname $ymdh;
    append arcvfname $uafilter(fm35_fext);

    # The wsfilter (uatomdf) depdens on this structure
    set savesubdir [file join $uafilter(fm35_dir) $ymd \
	$uafilter(fm35_hourly_subdir)];
    file mkdir $savesubdir;

    set arcvfile [file join $savesubdir $arcvfname];
    filterlib_file_append $arcvfile $rawdata;
}

filterlib_init;		# open the cpool if enabled
main $argc $argv;
filterlib_end;		# close the cpool if enabled
