#!/usr/bin/perl

use strict;
use warnings;

use Carp qw(confess);
use Date::Format;
use File::Basename;
use File::Copy;
use Getopt::Std;
#use File::stat;
use XML::LibXML;
use XML::LibXSLT;

use Ernad::Common;
use Ernad::Constant;
use Ernad::Dates;
use Ernad::Erimp;
use Ernad::Files;
use Ernad::Pages;

my %o;
&Getopt::Std::getopts('vf', \%o);
my $do_verbose = $o{'v'} // 0;
my $do_force = $o{'f'} // 0;

my $type='static_page';

my $impna=$ARGV[0];
if(not defined($impna)) {
  die "I need the impna.";
}
my $e=Ernad::Erimp->new({'impna'=>$impna});
if(not $e) {
  die "You geve me an invalid impna $impna\n";
}

my $www_dir=$e->{'dir'}->{'www'};
my $web_dir=$e->{'conf'}->{'www_dir'} // confess "I need this defined.";
## this may have the opt in it
my $web_opt_dir=$web_dir;
if(not $web_dir=~m|/opt|) {
  $web_opt_dir="$web_dir/opt";
}
#my $style_file=$e->{'dir'}->{'style'}.'/'.$type.$e->{'const'}->{'xsl_ext'};

## Testing creates XML pages before the transformation. This is done on the
## test machine only. We don't need testing for static pages. FixMe, the
## testing parameter should be renamed.
$e->{'testing'}='';

my $pretty_today=&Ernad::Dates::pretty_today;


foreach my $fufi (glob("$www_dir/*")) {
  if(-d $fufi) {
    if($do_verbose) {
      print "$fufi is a directory\n";
    }
    next;
  }
  if(not substr($fufi,-4) eq '.xml') {
    next;
  }
  my $file=$fufi;
  $file=~s|$www_dir||;
  chomp $fufi;
  if($do_verbose) {
    print "found $fufi\n";
  }
  my $out_file=$fufi;
  if(not $out_file=~s|$www_dir/|$web_opt_dir/|) {
    print "I can't change the directory for $fufi\n";
    next;
  }
  my $out_file_html=$out_file;
  $out_file_html=~s|\.xml|.html|;
  ## if the out file does not exist, remove it's dangling opt link too
  ##
  #&Ernad::Files::remove_dangling_opt_link_to_file($out_file);
  #&Ernad::Files::remove_dangling_opt_link_to_file($out_file_html);
  if(not -f $out_file_html) {
    my $no_opt_out_file=Ernad::Files::remove_opt($out_file_html);
    if(-l $no_opt_out_file) {
      &Ernad::Files::check_link($no_opt_out_file);
      if($do_verbose) {
        print "I delete the link $no_opt_out_file\n";
      }
      system("rm $no_opt_out_file");
    }
  }
  my $doc=$e->{'t'}->transform_file($fufi,'static_page',
                             {'update' => "'$pretty_today'",
                              'mod'=>"'changed'"});
  &Ernad::Pages::install($doc,$out_file_html);
}
