#!/opt/perl/bin/perl 
use strict;
use warnings;
use File::Basename;
use GPS::Defaults;
use GOA::StaSvec;
use GOA::StaPos;
use GOA::StaId;
use GOA::StaRcvr;
use GOA::StaLoc;
use GOA::Util;
use GPS::DATES;
use File::Copy;
use Getopt::Long;
use Cwd;
use Carp;
$SIG{ __DIE__ } = sub { Carp::confess( @_ ) };
my $progname = basename $0;
my $help = '';
my $no_mail = 0;
my $no_snx = 0;
my $no_nets = 0;
my $ow=1;
my $si = '';
my $usage = qq(

$progname [-info [svec|pos|loc|rcvr] ] [-no_mail] [-no_snx] [-no_nets] [-help]
 
Options :
  info    : only update this sta_info type (svec,pos,loc,rcvr)
  help    : this help
  
);
GetOptions(
            'info:s'   => \$si,
            'help'     => \$help,
            'overwrite' => \$ow,
           ) or die "Error in options\n";
           
if ( $help ) {
   die $usage;
   exit 1;
}
my %par = get_defaults();
my $dir = $par{STA_INFO_DIR};
my $today = get_date("today","cal");
my ($info,$file);
my @sta_info_files = qw/sta_svec sta_id sta_pos sta_loc sta_rcvr/;
   @sta_info_files = grep /$si/i,@sta_info_files if $si; 
#@sta_info_files = qw/sta_loc/;
chdir $dir; #  = $here;

foreach my $file ( @sta_info_files ) {
  #my @info_tmp = `ls $file.tmp* 2> /dev/null`; chomp @info_tmp;
  my @info_tmp = grep { /\.tmp/ } glob("$file*"); 
  next if ! @info_tmp;  
  foreach my $ftmp ( @info_tmp ) {
    #print "$dir $file $ftmp\n";
    #print "$ftmp ". -z $ftmp, "\n";
    unlink $ftmp if   -z $ftmp;
    next         if ! -e $ftmp;
    my %opt = ( file => "$dir/$file" );
    $info = $file eq 'sta_svec' ? GOA::StaSvec->new( %opt ) :
            $file eq 'sta_pos'  ? GOA::StaPos->new( %opt , overwrite => $ow ) :
            $file eq 'sta_id'   ? GOA::StaId->new( %opt ) :
            $file eq 'sta_rcvr' ? GOA::StaRcvr->new( %opt ) :
            $file eq 'sta_loc'  ? GOA::StaLoc->new( %opt ) :
                                '';
    if ( $info ) {       
      $info->load( file => "$dir/$ftmp" );
      $info->print( file => "$dir/$file.$today" );
      update_file( $file, $dir );
    }
  }
}

sub update_file {
 my $file = shift;
 my $here = shift;  
 my @old = grep ! /$today/, glob("$here/$file.*");
 
 print "found old $file :\n", join "\n",@old,"\n";
 
 if ( ! -d "$here/old" ) { 
     mkdir "$here/old" or die "$!\n"; 
 }
 
 foreach my $f ( @old ) { 
    move( $f, "$here/old"); 
 }
 
 unlink ("$here/$file") == 1 or warn "Couldn't unlink $file $@\n";
 
 #system("\\rm -f $here/$file");
 
 copy ("$here/$file.$today", "$here/$file");

}

  



   
