#!/usr/bin/perl -w

# Source: @RPM_PACKAGE_VERSION@-@RPM_PACKAGE_RELEASE@

BEGIN {
        unshift(@INC,($ENV{'POPHOME'}||'@POPHOME@').'/lib')
			unless $ENV{'KUNDE_NO_PERLPATH'};
      }

use utf8;
use strict;
use warnings;
use Umlaut qw(textmodus);

use Dbase::Help qw(DoSelect DoFn Do quote DoTime);
use Fehler qw(fehler report_fehler ffehler);
use Loader qw(reader writer export_fibunet_datum export_fibunet_zeit check_perm);
use Fcntl qw(O_RDONLY O_WRONLY O_EXCL O_CREAT);

sub Usage() {
	my $vers = '@RPM_PACKAGE_VERSION@-@RPM_PACKAGE_RELEASE@';

	textmodus(\*STDERR);
    die <<END;
Usage: $0 -- Spielt Pingpong zwischen Datenbank:fnbatch und FNBATCH.SCP
          -v    mit Protokollierung
          wo    Verzeichnis

Version: $vers
END
  exit 1;
}

use Getopt::Std;
use vars qw( $opt_h $opt_v $opt_m );
my $dir;
getopts("hvm:") or Usage;
Usage if $opt_h;
Usage if @ARGV != 1;

die "Das darfst du nicht\n" if $< and not check_perm("verwaltung");

if($opt_m) {
	chdir("/tmp");
	$dir = $ARGV[0];
} else {
	chdir($ARGV[0]) or fehler $ARGV[0],"nicht gefunden: $!";
}

sub umount() {
	return unless $opt_m;
	chdir("/tmp");
	system("umount $opt_m");
}
sub mount() {
	return unless $opt_m;
	return if chdir($dir);
	while(1) {
		system("mount $opt_m");
		return if chdir($dir);
		sleep(30);
	}
}

my $falsch=0;
$/="\r\n";
$|=1 if $opt_v;
my $done = 0;
my $omt = 0;

mount();

main:
while(1) {
  ffehler {
	print "  stat      \r" if $opt_v;
	my $mt = (stat("FNBATCH.SCP"))[9];
	if(not defined $mt) { # gibt es nicht
		$done = 0;
		my $fh = undef;
		print "  stat FEHLT    \r" if $opt_v;
		DoSelect {
			my($id,$tm,$budat,$mandant,$daten)=@_;
			$mandant = "0$mandant" if $mandant < 10;
			$mandant = "0$mandant" if $mandant < 100;
			$id = "0$id" if $id < 10;
			$id = "0$id" if $id < 100;

			print "Neu: $id                \n" if $opt_v;

			$daten =~ tr/äöüÄÖÜß/\204\224\201\216\231\232\341/;
			$daten =~ s/\n/\r\n/g;
			writer($daten,"FNBAT$mandant.$id");
			utime(DoTime-3*3600, DoTime-3*3600, "FNBAT$mandant.$id");
			unless($fh) {
				$fh = new IO::File("FNBATCH.TMP",O_WRONLY|O_CREAT|O_EXCL)
					or fehler "fnbatch.tmp","write","$!";
				print $fh "( ):FIBUNET\r\n";
			}
			Do("update fnbatch set status = 2 where id = $id");
			my $tmp = export_fibunet_zeit($tm||DoTime);
			$tm = export_fibunet_datum($tm||DoTime);
			$budat = export_fibunet_datum($budat||DoTime);
			print $fh qq#( ):$mandant;$budat;FNBAT$mandant.$id;$tm;$tmp\r\n#;
		} "select id,timestamp,buchen,mandant,daten from fnbatch where status = 1";
		if($fh) {
			$fh->close;
			utime(DoTime-3*3600, DoTime-3*3600, "FNBATCH.TMP");
			rename("FNBATCH.TMP","FNBATCH.SCP");
		}

	} elsif($mt == $omt) { # alt: prüfe auf Fehler
		$done = 1 if $done == 0;
		print "  stat ALT      \r" if $opt_v;

		my %id;
		my $fh = new IO::File("FNBATCH.SCP",O_RDONLY)
			or fehler "fnbatch.scp","read","$!";
		my $line = <$fh>;
		fehler "fnbatch.scp","content",$line if $line ne "( ):FIBUNET\r\n";
		while(<$fh>) {
			chomp $_;
			if(/^\(([ ?+])\):.*;FNBAT(?:\d\d\d).(\d\d\d);/) {
				my $was = $1;
				my $id = $2;
				if($was eq " ") {
					$done = 0;
					$id{$id} = 2; # noch offen
				} elsif($was eq "+") {
					$id{$id} = 4; # fertig
				} else {
					$id{$id} = 3; # Fehler
				}
			}
		}
		$fh->close;
		DoSelect {
			my($id,$mandant) = @_;
			$mandant = "0$mandant" if $mandant < 10;
			$mandant = "0$mandant" if $mandant < 100;
			$id = "0$id" if $id < 10;
			$id = "0$id" if $id < 100;

			my $ids = $id{$id};
			return if not $ids or $ids == 2; ## noch in Arbeit

			my $fehler = "?";
			my $fd = new IO::File("FNBATCH.PTK");
			if(ref $fd) {
				ml:
				while(<$fd>) {
					chomp;
					tr/\204\224\201\216\231\232\341/äöüÄÖÜß/;
					if(/Starte Übernahme \(Mandant $mandant\/.*\/Datei FNBAT$mandant\.$id/ or /Starte Übernahme\..*Parameter: FNBAT$mandant\.$id 00$mandant.*\s(\d\d\dPN\d\d\d\.\d\d\d)/) {
						my $pna = ""; $pna = "(PNA:$1)" if defined $1;
						next unless /^<\d\d\.\d\d\.\d\d-\d\d:\d\d:\d\d-([^-]+)-/;
						$fehler = $_.$pna;
						my $user = $1;
						while(<$fd>) {
							chomp;
							tr/\204\224\201\216\231\232\341/äöüÄÖÜß/;
							if(/Starte Übernahme \(Mandant $mandant\/.*\/Datei FNBAT$mandant\.$id/ or /Starte Übernahme\..*Parameter: FNBAT$mandant.$id 00$mandant/) {
								tr/äöüÄÖÜß/\204\224\201\216\231\232\341/;
								redo ml;
							}
							next unless /^<\d\d\.\d\d\.\d\d-\d\d:\d\d:\d\d-([^-]+)-/;
							next if $user ne $1;
							$fehler = $_.$pna; next ml;
						}
					}
				}
				$fd->close;
			}
			$fehler =~ s/^<[^>]+>\s*//;
			Do("update fnbatch set fehler = '${\quote $fehler}' where id = $id");
			if(-f "FNBAT$mandant.$id") {
				my $daten = reader("FNBAT$mandant.$id");
				fehler "FNBAT$mandant.$id","Lesefehler" unless defined $daten;
				$daten =~ s/\r\n/\n/g;
				$daten =~ tr/\204\224\201\216\231\232\341/äöüÄÖÜß/;

				Do("update fnbatch set daten='${\quote $daten}' where id = $id");
				unlink("FNBAT$mandant.$id");
			}
			print "Done: $id: $ids           \n" if $opt_v;
			Do("update fnbatch set status = $ids where id = $id");
		} "select id,mandant from fnbatch where status = 2";
		unlink("FNBATCH.SCP") if $done > 2;
		$done++ if $done;
	} else {
		print "  stat NEU      \r" if $opt_v;
		$omt = $mt;
		$done = 1;
	}
	next;  ## "next main;" -- führte zu Runtimefehler  :-(
  } sub {
	report_fehler,exit(9) if $falsch or $opt_v;
	$falsch++;
	Do("delete from fnbatch where id = 0");
	Do("insert into fnbatch set art='Fehler!',id=0,timestamp=UNIX_TIMESTAMP(NOW()), status=3,daten='".quote(join("\n",@_))."'");
	$falsch--;
  };

} continue {
	print " _\r" if $opt_v;
	if(DoFn("select count(*) from fnbatch where status=2") != 0) {
		sleep(3);
	} else {
		umount();
		sleep 10 while DoFn("select count(*) from fnbatch where status=1") == 0;
		mount();
	}
}
