#!/usr/bin/env perl
use strict;
use warnings;
use File::Find;
use File::Copy qw(copy);
use File::Path qw(make_path);
use File::Basename;
use File::Spec;
use Getopt::Long;

my $pdf  = 0;
my $html = 0;

GetOptions(
	'pdf'  => \$pdf,
	'html' => \$html,
) or die "Usage: $0 [--pdf] [--html] [file.tex ...]\n";

my $texinputs = $ENV{TEXINPUTS};

my @texfiles = @ARGV;
if (!@ARGV){
	@texfiles = glob("*.tex");
}

# Unter Windows ist es ein Semikolon (;), unter Unix meist Doppelpunkt (:)
# Unter WSL werden ENV Vars übernommen, aber ; bleibt bestehen.
my $sep = ($^O eq 'MSWin32' or `uname -r` =~ /Microsoft/i) ? ';' : ':';
my ($LatexGlobal) = split /\Q$sep\E/, $texinputs;

# Codepage auf UTF-8 setzen, falls unter Windows
system("chcp 65001 >NUL") if $^O eq 'MSWin32';

my @search_paths = ($LatexGlobal, '.');


# Konvertiere alle pdfs zu svgs
print("-----------------------------------------------\n");
print "Konvertiere alle pdfs zu svgs\n";
print("-----------------------------------------------\n");
for my $base (@search_paths){
	next unless -d $base;
	
	find({
	wanted => sub{
		return unless -f;
		return if $File::Find::name =~ m{./html}i;
		
		# Prüfen, ob gleichnamiges .tex existiert
		my ($name, $dir, $ext) = fileparse($File::Find::name, qr{\.[^.]*});
		my $texfile = File::Spec->catfile($dir, "$name.tex");
		my $svgfile = File::Spec->catfile($dir, "$name.svg");

		if ($File::Find::name =~ /.*\.pdf/i){
			if (-e $texfile) {
				print "Überspringe $File::Find::name, da $texfile existiert\n";
				return;
			}
			if (-e $svgfile){
				print "Überspringe $File::Find::name, da svg bereits existiert\n";
				return;
			}
			
			system('lwarpmk', 'pdftosvg', $File::Find::name);
		}
	}, no_chdir => 1
	}, $base);
}


sub copy_dir {
	print("Kopiere $_[0] zu $_[1] \n");
	# Perl kann Ordner ohne extra Module nicht Plattformunabhängig kopieren.
	if ($^O eq 'MSWin32'){
		system("xcopy \"$_[0]\" \"$_[1]\" /E /I /Y ");
	} else {
		system("cp -r \"$_[0]\" \"$_[1]\"");
	}
}

my $mathjax_source = File::Spec->catfile($LatexGlobal, "tex4ht", "mathjax");
my $fonts_source = File::Spec->catfile($LatexGlobal, "tex4ht", "fonts");


my $make4htBUILD = File::Spec->catfile($LatexGlobal, "tex4ht", "html.mk4");
my $tex4htCFG = File::Spec->catfile($LatexGlobal, "tex4ht", "html.cfg");

if (($^O eq 'MSWin32' or `uname -r` =~ /Microsoft/i)){
	# Wenn Windows oder WSL, ersetze Backslashes durch Slashes
	# tex4ht kommt nicht mit Backslashes klar...
	$tex4htCFG =~ s!\\!/!g;
}

for my $texfile (@texfiles){
	next if $texfile =~ m{.*_html.tex};
	my ($basename, $dir, $ext) = fileparse($texfile, qr/\.[^.]*/);
	print("\n\n-----------------------------------------------\n");
	print("Building $texfile\n");
	print("-----------------------------------------------\n");

	if (($pdf == 0 and $html == 0) or $pdf == 1){
		system("latexmk", "\"".$texfile."\"");
	}

	if (($pdf == 0 and $html == 0) or $html == 1){
		print("Basename: ".$basename."\n");
		my $html_dest = File::Spec->catfile("html", $basename);
		make_path($html_dest);
		my $mathjax_dest = File::Spec->catfile($html_dest, "tex4ht", "mathjax");
		copy_dir($mathjax_source, $mathjax_dest);

		my $fonts_dest = File::Spec->catfile($html_dest, "tex4ht", "fonts");
		copy_dir($fonts_source, $fonts_dest);
		
		system("make4ht", "-c", $tex4htCFG, "-d", $html_dest, "-f", "html5", "-e", $make4htBUILD, "-uls", "--loglevel", "debug", $texfile);
	}
}


print("\n Fertig :)\n")
