#!/usr/bin/perl

require "/home/pi/smarthome/library.pl";
$maxlen = 200;
$debug = 0;

# https://www.biblestudytools.com/cuvs/romans/6-20.html
# https://www.biblestudytools.com/elb/romans/6-20.html
# https://www.biblestudytools.com/esv/romans/6-20.html

# define available books
# asv: American Standard Version
# cuvp: Chinese Union Version - Pinyin
# cuvs: Chinese Union Version - Simplified
# ceb: Common English Bible
# elb: Elberfelder 1905 (German)
# esv: English Standard Version
# gw: GOD&#39;S WORD Translation
# gnt: Good News Translation
# hnv: Hebrew Names Version
# kjv: King James Version
# leb: Lexham English Bible
# lsg: Louis Segond 1910 (French)
# lut: Luther Bible 1912 (German)
# nas: New American Standard Bible
# ncv: New Century Version
# nirv: New International Reader&#39;s Version
# niv: New International Version
# nkjv: New King James Version
# nlt: New Living Translation
# nrs: New Revised Standard
# ojb: Orthodox Jewish Bible
# ost: Ostervald (French)
# rhe: Douay-Rheims Catholic Bible
# rsv: Revised Standard Version
# sblg: SBL Greek New Testament
# lxx: Septuagint Bible w/ Apocrypha
# bbe: The Bible in Basic English
# cjb: The Complete Jewish Bible
# vul: The Latin Vulgate
# msg: The Message Bible
# wbt: The Webster Bible
# tmb: Third Millennium Bible
# tyn: Tyndale4
# wnt: Weymouth New Testament
# web: World English Bible
# wyc: Wycliffe
# ylt: Young&#39;s Literal Translation
@versions = qw(cuvs elb esv asv ceb cuvp gnt gw hnv kjv leb lsg lut nas ncv nirv niv nkjv nlt nrs ojb ost rhe rsv sblg lxx bbe cjb vul msg wbt tmb tyn wnt web wyc ylt);
$verlangs{"lsg"} = "fr";
$verlangs{"cuvp"} = "cn";
$verlangs{"cuvs"} = "cn";
$verlangs{"elb"} = "de";
$verlangs{"lut"} = "de";
$verlangs{"sblg"} = "gr";
$verlangs{"pdf"} = "he";

# define possible book abbreviations: the last name is the full german name
@books_ot = ("Genesis|Gen|Ge|Gn|1Mose|Genesis", "Exodus|Ex|Exod|Exo|2Mose|Exodus", "Leviticus|Lev|Le|Lv|3Mose|Leviticus", "Numbers|Num|Nu|Nm|Nb|4Mose|Numeri", "Deuteronomy|Deut|De|Dt|5Mose|Deuteronomium", "Joshua|Josh|Jos|Jsh|Josua", "Judges|Judg|Jdg|Jg|Jdgs|Richter", "Ruth|Rth|Ru", "1Samuel|1Sam|1Sa|1Sm|1Samuel", "2Samuel|2Sam|2Sa|2Sm|2Samuel", "1Kings|1Kgs|1Kg|1Kin|1Kn|1Kön|1Koenige|1Koen|1Könige", "2Kings|2Kgs|2Kg|2Kin|2Kn|2Kön|2Koenige|2Koen|2Könige", "1Chronicles|1Chron|1Chr|1Ch|1Chroniken|1Chronik", "2Chronicles|2Chron|2Chr|2Ch|2Chroniken|2Chronik", "Ezra|Ezr|Ez|Esra", "Nehemiah|Neh|Ne|Nh|Nhm|Nehemia", "Esther|Est|Esth|Es|Ester", "Job|Jb|Hb|Hi|Hiob", "Psalms|Pslm|Psa|Psm|Pss|Ps|Psalmen|Psalm", "Proverbs|Prov|Pro|Prv|Pr|Sprüche|Spr|Sp|Sprueche", "Ecclesiastes|Eccles|Eccle|Ecc|Ec|Qoh|Pre|Pred|Prg|Pr|Prediger", "Song of Solomon|Song|Song of Songs|SOS|So|Canticle of Canticles|Canticles|Canticle|Cant|Ct|Can|Hoheslied|Hohes Lied|Lied|Hl|Hohelied", "Isaiah|Isa|Is|Jes|Jesaja", "Jeremiah|Jer|Je|Jr|Jeremia", "Lamentations|Lam|La|Klage|Klgl|Klg|Kl|Klagelieder", "Ezekiel|Ezek|Eze|Ezk|Hes|Hsk|He|Hesekiel", "Daniel|Dan|Da|Dn|Daniel", "Hosea|Hos|Ho|Hosea", "Joel|Jl|Joe|Joel", "Amos|Amo|Am|Amos", "Obadiah|Obad|Ob|Obadja", "Jonah|Jnh|Jon|Jona", "Micah|Mic|Mc|Mich|Mi|Micha", "Nahum|Nah|Na|Nhm|Nahum", "Habakkuk|Habakukk|Haba|Hab|Hbk|Ha|Habakuk", "Zephaniah|Zeph|Zep|Zp|Zef|Ze|Zefanja", "Haggai|Hag|Hg|Hagai", "Zechariah|Zech|Zec|Zc|Sach|Sac|Sa|Sacharja", "Malachi|Mal|Ml|Maleachi");
@books_nt = ("Matthew|Matt|Mt|Matthaeus|Matth|Mth|Matthaus", "Mark|Mrk|Mar|Mk|Mr|Markus", "Luke|Luk|Lk|Lukas", "John|Joh|Jhn|Jn|Johannes", "Acts|Act|Ac|Apg|Apostelgeschichte", "Romans|Rom|Ro|Rm|Röm|Römer|Roemer|Roem|Romans|Romer", "1Corinthians|1Cor|1Co|1Cr|1Korinth|1Kor|1Kr|1Korinther", "2Corinthians|2Cor|2Co|2Cr|2Korinth|2Kor|2Kr|2Korinther", "Galatians|Gal|Ga|Galater", "Ephesians|Eph|Ephes|Epheser", "Philippians|Phil|Php|Pp|Philipper", "Colossians|Col|Co|Kol|Kolosser", "1Thessalonians|1Thess|1Thes|1Th|1Ths|1Thessa|1Tessa|1Tess|1Tes|1Ts|1Thessalonicher", "2Thessalonians|2Thess|2Thes|2Th|2Ths|2Thessa|2Tessa|2Tess|2Tes|2Ts|2Thessalonicher", "1Timothy|1Tim|1Ti|1Tm|1Timo|1Timotheus", "2Timothy|2Tim|2Ti|2Tm|2Timo|2Timotheus", "Titus|Tit|Ti|Tt|Titus", "Philemon|Philem|Phm|Pm|Philemon", "Hebrews|Heb|He|Hebraer|Hebr|Hbr|Hebraer", "James|Jas|Jm|Jakob|Jacob|Jak|Jac|Jk|Jc|Jakobus", "1Peter|1Pet|1Pe|1Pt|1Petr|1Petrus", "2Peter|2Pet|2Pe|2Pt|2Petr|2Petrus", "1John|1Joh|1Jhn|1Jn|1Johannes", "2John|2Joh|2Jhn|2Jn|2Johannes", "3John|3Joh|3Jhn|3Jn|3Johannes", "Jude|Jud|Jd|Judas", "Revelation|Rev|Re|Rev|Offenb|Off|Ofb|Offb|Offbg|Offenbarung");


# fix sth like: 1 kor 13,10 => 1 kor 13 10
for($i=0;$i<$#ARGV+1;$i++){
	usage() if($ARGV[$i]=~/^\-?\-h/);
	$arg = $ARGV[$i];
	$arg =~ s/und|u\.|\+/-/i;
	if($arg=~/oneline/){
		$oneline = 1;
	} elsif($arg=~/[,:]/){
		push(@args, split(/\s*[,:]\s*/, $arg));
	} else{
		push(@args, $arg);
	}
}
println("- given args: ". join(", ", @args)) if($debug);

# try at first to get books starting with a number, eg. 1 Kor => 1 Corinthians
for($i=0;$i<$#args+1;$i++){
	$arg = $args[$i];
	next if($arg!~/^\d/);
	$arg2 = $args[$i+1];
	$search = $arg ." ". $arg2;
	$book = getBook($search);
	if($book=~/\S/){
		splice(@args, $i+1, 1);
		splice(@args, $i, 1);
		last;
	}
}
println("- 1st try getting a book gave: $book") if($debug);

# identify a book (without preceding number)
if($book!~/\S/){
	for($i=0;$i<$#args+1;$i++){
		$search = $args[$i];
		$search =~ s/^(\d)\.?\s*(\S.+)$/$1$2/;
		$book = getBook($search);
		if($book=~/\S/){
			splice(@args, $i, 1);
			last;
		}
	}
}
println("- 2nd try getting a book gave: $book") if($debug);
usage("found no book!") if($book!~/\S/);

println("- left-over args: ". join(", ", @args)) if($debug);



# identify a language, if given
$langgiven = 0;
for($i=0;$i<$#args+1;$i++){
	$arg = trim($args[$i]);
	if($lang!~/\S/){
		$lang = "en" if($arg=~/en/i);
		$lang = "gr" if($arg=~/gr/i);
		$lang = "fr" if($arg=~/fr/i);
		$lang = "he" if($arg=~/he/i);
		$lang = "de" if($arg=~/de/i or $arg=~/ge/i);
		$lang = "cn" if($arg=~/ch/i or $arg=~/cn/i or $arg=~/zh/i);
		if($lang=~/\S/){
			splice(@args, $i, 1);
			$langgiven = 1;
			last;
		}
	}
}
if($lang eq "gr"){
	$found = 0;
	for($b=0;$b<$#books_nt+1;$b++){
		@booknames = split(/\|/, $books_nt[$b]);
		for($n=0;$n<$#booknames+1;$n++){
			$found = 1 if(lc($booknames[$n]) eq lc($book));
		}
	}
	die("ERROR: found no greek book ($book)!") if(!$found);
}
println("- the language $lang was discovered in the arguments") if($debug and $langgiven);
println("- no language was discovered in the arguments, so we define it later ...") if($debug and !$langgiven);
println("- left-over args: ". join(", ", @args)) if($debug);


# identify a version, if given
$version = ""; $versiongiven = 0;
for($i=0;$i<$#args+1;$i++){
	$arg = trim($args[$i]);
	for($j=0;$j<$#versions+1;$j++){
		$v = $versions[$j];
		if($v eq $arg){
			$version = $v;
			$lang = "en";
			$lang = $verlangs{$v} if(exists($verlangs{$v}));
			$versiongiven = 1;
			splice(@args, $i, 1);
			last;
		}
		last if($versiongiven);
	}
}
println("- the translation $version was discovered in the arguments, so the language is $lang") if($debug and $versiongiven);
println("- no translation was discovered in the arguments") if($debug and !$versiongiven);
println("- left-over args: ". join(", ", @args)) if($debug);


# get chapter and vers
if($book eq "Jude" or $book eq "Obadiah" or $book eq "Philemon" or $book eq "2 John" or $book eq "3 John"){
	println("- the book discovered is has only 1 chapter ...") if($debug);
	$chapter = 1;
	$numberargs = 0;
	for($i=0;$i<$#args+1;$i++){
		if($args[$i]=~/^\d+,\d+$/){
			println("- this argument will be pushed as two arguments: ". $args[$i]) if($debug);
			splice(@args, $i, 1, split(/,/, $args[$i]));
			$i++;
		}
	}
	for($i=0;$i<$#args+1;$i++){
		$numberargs++ if($args[$i]=~/^\d+/);
	}
	println("- left-over args: ". join(", ", @args) ." ($numberargs numeric arguments)") if($debug);
	for($i=0;$i<$#args+1;$i++){
		$arg = trim($args[$i]);
		if(int($arg)==1 and $numberargs>1){
			println("- the arg number $i contains a '1', and it must mean the chapter 1 (since we have $numberargs args), so we remove it") if($debug);
			splice(@args, $i, 1);
			last;
		}
	}
} else{
	for($i=0;$i<$#args+1;$i++){
		$arg = trim($args[$i]);
		if($arg=~/^\d/){
			println("- arg number $i will be cleansed from any non-numeric and will serve as chapter definition") if($debug);
			if($chapter!~/\S/){
				$arg =~ s/\D//g;
				$chapter = $arg;
				splice(@args, $i, 1);
				last;
			}
		}
	}
}
println("- chapter definition: $chapter") if($debug);
println("- left-over args: ". join(", ", @args)) if($debug);

@verses = ();
$versinfo = "";
$arg = trim(join("", @args));
println("- left-over args (as string): $arg") if($debug);
if($arg=~/^\d/){
	println("- it serves as verse definition") if($debug);
	$arg =~ s/[au]nd|[au]\./+/i;
	$arg =~ s/([abcd])[au]/$1+/i;
	$versinfo = $arg;
	if($arg=~/\+/){
		println("- it contains a '+' (maybe originally a 'und', 'and', 'u.', 'a.')") if($debug);
		push(@verses, split(/\s*\+\s*/, $arg));
	}
	elsif($arg=~/\-/){
		println("- it contains a range") if($debug);
		($nr1, $nr2) = split(/\s*\-\s*/, $arg);
		for($n=$nr1;$n<=$nr2;$n++){
			push(@verses, $n);
		}
	}
	else{
		println("- it will be taken as pure verse definition") if($debug);
		push(@verses, $arg);
	}
}
println("- identified following verses: ". join(", ", @verses)) if($debug);
println("- vers info: $versinfo") if($debug);
usage("found no chapter/vers for book $book!") if($#verses<0);


# testing
if($book!~/\S/ or $#verses<0){
	$book = "rom";
	$chapter = 1;
	$vers = 1;
}

# bible translations
$lang = "de" if($lang!~/\S/ or $lang=~/ge/i);
println("- the language has been fixed to: $lang") if($debug);
if($version!~/\S/){
	$version = "elb";
	$version = "esv" if($lang=~/en/i);
	$version = "cuvs" if($lang=~/cn/i);
	$version = "lsg" if($lang=~/fr/i);
	$version = "sblg" if($lang=~/gr/i);
	$version = "pdf" if($lang=~/he/i);
}
println("- sinces no translation was discovered in the arguments, we set it to $version (due to the language '$lang')") if($debug and !$versiongiven);

# wget
$searchbook = $book;
$searchbook = getGermanBook($searchbook) if($lang eq "de");
println("- the german book is: $searchbook") if($lang eq "de" and $debug);
$searchbook = getChineseBook($searchbook) if($lang eq "cn");
println("- the chinese book is: $searchbook") if($lang eq "cn" and $debug);
$searchbook = getFrenchBook($searchbook) if($lang eq "fr");
println("- the french book is: $searchbook") if($lang eq "fr" and $debug);
$searchbook = getHebrewBook($searchbook) if($lang eq "he");
println("- the french book is: $searchbook") if($lang eq "he" and $debug);
$searchbook = lc($searchbook);
$searchbook =~ s/\s+/-/g;
$searchbook =~ s/[^\d\-\w]//g;
println("- the book to search for has been changed to: $searchbook") if($debug);

$url = "https://www.biblestudytools.com/$version/$searchbook/$chapter.html";
$url = "https://www.scripture4all.org/OnlineInterlinear/OTpdf/$searchbook$chapter.pdf" if($lang eq "he");
$outfile = "$budir/bibleonline.htm";
$outfile = "$budir/bibleonline.pdf" if($lang eq "he");
$tmpfile = "$budir/bibleonline.tmp";
$cmd = "wget --local-encoding=UTF8 -O $outfile -o $tmpfile '$url'";
println("- the wget call is: $cmd") if($debug);
system("$cmd");


if($lang eq "he"){
	println("- double click to download bibleonline.pdf");
	exit 0;
}


#system("iconv --from-code=UTF-8 --to-code=ISO-8859-1 $outfile 2>&1 >$tmpfile; mv $tmpfile $outfile") if($lang ne "cn");
println("- analyse the output ...") if($debug);
open(F, "<$outfile") or printAndDie("ERROR: cannot read file $outfile: $!");
$start = 0;
while(<F>){
	$line = trim($_);
	last if($start and ($line=~/Facebook/i or $line=~/^<div class=.+justify-center/));
	if($line=~/class=\"\s*bible-verses\s*\"/){
		$start = 1;
		next;
	}
	next if(!$start);
	# $quotes{$v} $quotes{16} ...
	if($line=~/data-verse-id=\"(\d+)\"/){
		$v = $1;
		next;
	}
	$line =~ s/<a href=\"#references-crossreferences\">\d+<\/a>//g;
	next if($line=~/^<div\s*$/ or $line=~/class=\"leading-8 rounded my-1 \"/ or $line=~/<a x-show=\"verseNumbers\" class=\"text-blue-600 font-bold inline-block\"/ or $line=~/href=\"https:\/\/www.biblestudytools.com/ or $line=~/^<\/a>\s*$/ or $line=~/^<\/div>\s*$/);
	$line =~ s/<[^>]+>//g;
	$line =~ s/\"\s*$//g;
	$line = trim($line);
	next if($line!~/\S/ or $line=~/^\d+$/ or $line=~/^<a x-show/ or $line=~/^class=\"font-sans/);
	println("- $v: ". $line) if($debug);
	$quotes{$v} = $line;
}
close(F);

println("- one more time: the given book was: $book") if($debug);
$book = camelCase($book);
println("- the given book was changed to: $book") if($debug);

$book = getGermanBook($book) if($lang eq "de");
$book = getChineseBook($book) if($lang eq "cn");
$book = getFrenchBook($book) if($lang eq "fr");
println("- the given book was changed to: $book") if($debug and $lang eq "de");

println("$book $chapter, $versinfo:");
for($v=0;$v<$#verses+1;$v++){
	$vers = $verses[$v];
	println("- vers $vers ...") if($debug);
	$vers =~ s/[abcd]$//;
	println("	- changed to: vers $vers ...") if($debug);
	$quote = $quotes{$vers};
	println("	- text: $quote ...") if($debug);
	$quote =~ s/([\.,!;:\-\?\)\(])([a-zA-Z])/$1 $2/g;
	println("	- changed to text: $quote ...") if($debug);
	$quote =~ s/.quot;/"/g;
	println("	- changed to text: $quote ...") if($debug);
	$quote =~ s/^\s*(\(\d+\))\s*\"/$1 /g;
	println("	- changed to text: $quote ...") if($debug);
	$quote = trim($quote);
	println("	- changed to text: $quote ...") if($debug);
	push(@output, "($vers) $quote");
}

println("- printing out ...") if($debug);
if($oneline){
	println(prepareOutput(join(" ", @output)));
} else{
	for($v=0;$v<$#output+1;$v++){
		$line = $output[$v];
		$len = length($line); # e.g. 240
		$rows = int($len/$maxlen) + 1; # e.g. 240/200+1 = 2
		for($n=0;$n<$rows;$n++){ # 0*200 - 1*200
			println(prepareOutput(substr($line, $n*$maxlen, $maxlen)));
		}
	}
}


sub prepareOutput{
	my $str = shift;
	$str =~ s/\s+//g if($lang eq "cn");
	return $str;
}

sub getBook{
	my $search = shift;
	$search = trim($search);
	$search =~ s/^(\d)[\.e]?r?\s+/$1/;
	$search =~ s/\s+//g;
	my $book = "";
	my @books = @books_ot;
	push(@books, @books_nt);
	for(my $b=0;$b<$#books+1;$b++){
		my @abbr = split(/\|/, $books[$b]);
		for(my $a=0;$a<$#abbr+1;$a++){
			if($abbr[$a]=~/^$search\b/i and $search=~/\D/){
				$book = trim($abbr[0]);
				last;
			}
		}
		last if($book=~/\S/);
	}
	$book =~ s/^(\d+)(\S)/$1 $2/;
	return $book;
}
sub getGermanBook{
	my $book = shift;
	my $debook = $book;
	$book =~ s/^(\d)\s+(\S.+)$/$1$2/;
	my @books = @books_ot;
	push(@books, @books_nt);
	for(my $b=0;$b<$#books+1;$b++){
		my @abbr = split(/\|/, $books[$b]);
		if(lc($abbr[0]) eq lc($book)){
			$debook = $abbr[-1];
			last;
		}
	}
	$debook =~ s/^(\d)\.?\s*(\S.+)$/$1. $2/;
	return $debook;
}
sub getChineseBook{
	my $book = shift;
	my $cnbook = $book;
	my @cnbooks = qw(chuangshiji chuaijiji liweiji minshuji shenmengji yueshuyaji shishiji ludeji samuerjishang samuerjixia liewangjishang liewangjixia lidaizhishang lidaizhixia yisilaji niximiji yisitieji yuebo shipian zhenyan chuandaoshu yage yisaiyashu yelimishu yelimiaige yisijieshu danyilishu hexiashu yueershu amosishu ebadiyashu yuenashu mijiashu nahongshu habagushu xifanyashu hagaishu sajialiyashu malajishu mataifuyin makefuyin lujiafuyin yuehanfuyin shituxingzhuan luomashu gelinduoqianshu gelinduohoushu jialataishu yifusuoshu feilibishu geluoxishu tiesaluonijiaqianshu tiesaluonijiahoushu timotaiqianshu timotaihoushu tiduoshu feilimenshu xibolaishu yageshu bideqianshu bidehoushu yuehanyishu yuehanershu yuehansanshu youdashu qishilu);
	my @books = @books_ot;
	push(@books, @books_nt);
	for(my $b=0;$b<$#books+1;$b++){
		my @abbr = split(/\|/, $books[$b]);
		if(lc($abbr[0]) eq lc($book)){
			$cnbook = $cnbooks[$b];
			last;
		}
	}
	return $cnbook;
}
sub getFrenchBook{
	my $book = shift;
	my $frbook = $book;
	my @frbooks = qw(genese exode levitique nombres deuteronome josue juges ruth 1-samuel 2-samuel 1-rois 2-rois 1-chroniques 2-chroniques esdras nehemie esther job psaume proverbes ecclesiaste cantique-des-cantiqu esaiejeremie lamentations ezekiel daniel osee joel amos abdias jonas michee nahum habacuc sophonie aggee zacharie malachie matthieu marc luc jean actes romains 1-corinthiens 2-corinthiens galates ephesiens  philippiens colossiens 1-thessaloniciens 2-thessaloniciens 1-timothee 2-timothee tite philemon hebreux jacques 1-pierre 2-pierre 1-jean 2-jean 3-jean jude apocalypse);
	my @books = @books_ot;
	push(@books, @books_nt);
	for(my $b=0;$b<$#books+1;$b++){
		my @abbr = split(/\|/, $books[$b]);
		if(lc($abbr[0]) eq lc($book)){
			$frbook = $frbooks[$b];
			last;
		}
	}
	return $frbook;
}
sub getHebrewBook{
	my $book = shift;
	my $hebook = $book;
	my $found = 0;
	my @hebooks = qw(gen exo lev num deu jos jdg rut 1sa 2sa 1kg 2kg 1ch 2ch ezr neh est job psa pro qoh can isa jer lam eze dan hos joe amo oba jon mic nah hab zep hag zec mal);
	my @books = @books_ot;
	for(my $b=0;$b<$#books+1;$b++){
		my @abbr = split(/\|/, $books[$b]);
		if(lc($abbr[0]) eq lc($book)){
			$hebook = $hebooks[$b];
			$found = 1;
			last;
		}
	}
	die("ERROR: could not find a hebrew book!") if(!$found);
	return $hebook;
}
sub camelCase{
	my $str = shift;
	return uc(substr($str, 0, 1)) . substr($str, 1);
}
sub usage{
	my $str = shift;
	my $rc = 0;
	println("usage: $0 [book] [chapter] [vers] [lang: de|en|cn|fr|gr, default: de] [translation] [oneline]");
	if($str=~/\S/){
		println("ERROR: $str");
		$rc = 1;
	}
	exit $rc;
}
