#!/usr/bin/perl 



#
#
#
# Best viewed with TAB = 3 spaces.
#
#
#


my $VERSION;
$VERSION="2.1";

use strict;
use warnings;
use Image::Magick;
use DBI;
use Getopt::Long;
use fontlinge::Filebasics;
use fontlinge::Fontling;
use File::Find;
use Cwd 'abs_path';

use bytes;

$|=1;



#
#	Config init
#
	my $make_previews=0;
	my $force_previews=0;
	my $copy=0;
	my $percent;
	my $move=0;
	my $look=0;
	my $insert_into_database=0;
	my $keep_database;
	my $help;
	my $debug=0;
	my $verbose;
	my $rename_otf=0;
	my $HOME;
#	my $my_preview;
#	my $my_preview_path;
	my $my_preview_suffix;
	my $my_code;


GetOptions (	'previews'		=> \$make_previews,
 		'forcepreviews' 	=> \$force_previews,
 		'copy'	 		=> \$copy,
 		'percent' 		=> \$percent,
 		'move' 			=> \$move,
 		'rename-otf|rename_otf'			=> \$rename_otf,
 		'look' 			=> \$look,
 		'dbinsert'		=> \$insert_into_database,
 		'dbkeep'		=> \$keep_database,
 		'debug' 		=> \$debug,
 		'verbose|v'		=> \$verbose,
 		'my-code|my_code=s'		=> \$my_code,
 		'my-preview-suffix=s'		=> \$my_preview_suffix,
 		'fontbase=s'		=> \$HOME,
		'help'			=> \$help
 ) || exit -1 ;



my %config		=	fontlinge_Get_Config();




# implement userdefined code
#
if( ! $my_code && $config{'my_code' } ) { 
	$my_code = $config{'my_code'};
}
if( $my_code ) { 
	$my_code = fontlinge_My_Path( $my_code ,$config{'my_code' }, 'my_code' ); # cleanup the path
	fontlinge_My_Code( $my_code );	# overwrite subroutines with MY_* subs
	fontlinge_HOOK_Init();
}




if ( $verbose && $percent ) {
	print "Use --percent OR --verbose.\n\n";
	exit;
}
fontlinge_Verbose( $verbose );

if ($help) {
	&usage;
	exit;
}

if ( $copy + $move + $insert_into_database + $make_previews + $look != 1 ) {
	print "Use exactly one command each time.\n\n";
	&usage;
	exit 1;
}



if ( ! $keep_database)			{ $keep_database=0; }


if (! defined $HOME) { $HOME=$config{'fontbase'};}

if( ! defined $HOME) {
	print STDERR "FATAL ERROR: \$HOME not defined!\n";
	exit -1;
}
$HOME = fontlinge_Expand_Filename($HOME,'path');

if( $HOME!~/\/$/ ) {
	$HOME.="/";
}


my $err="";
my $filename;
my $filesize;
my $file;
my $dbh;
my $sth;
my $make_dirs=($copy+$move==0?0:1);
my %font;
my @fontnames;
my $kategorie;
my $kategorie_nr;
my @kategorie;
my $hashname;
my @dest_path;
my $dest_path;
my $newname;
my $tmp;
my $just_made_dir;
my $preview_made;

my $base ; my $path ; my $type ;
my $number="";

my @file_list=@ARGV;
my @file_list2;



if ( (@file_list) == 1) {
		if( ! -d $file_list[0]) {
			print "\nArgument is not a folder.\n";
			&usage;
			exit;
		}
		
		my @seekdirs=( abs_path($file_list[0]) );
		@file_list=();
		$File::Find::dont_use_nlink=1;
		find(\&wanted, @seekdirs );
} else {
	print "\nPlease give exactly one folder as argument.\n";
	&usage;
	exit;
}

#
# Get a list of files to work on. OpenType / TrueType is handled "as is".
# PostScript families are checked for the mosted usable file
#

for( my $i=0 ; $i< (@file_list) ; $i++ ) {
	($base,$path,$type) = fontlinge_Fileparse($file_list[$i]);
	if ( 	(uc $type eq ".TTF") ||
			(uc $type eq ".OTF")
	 ) {
		$file_list2[(@file_list2)]=$file_list[$i];
	} else {
		$tmp="";
		foreach my $x ("mmm","MMM","inf","INF","cfg","CFG","afm","AFM","pfm","PFM","pfa","PFA","pfb","PFB") {
			if (-e "$path$base.$x") {
				$tmp="$path$base.$x";
			}
		}
		if ($tmp ne '') {
			$file_list2[(@file_list2)]=$tmp;
		}		
	}
}


#
# remove duplicate folders
#
@file_list=();
@file_list2=sort @file_list2;
$file_list[0]=$file_list2[0];
for( my $i=0 ; $i< (@file_list2) ; $i++ ) {
	if ($file_list2[$i] ne $file_list[(@file_list)-1]) {
		$file_list[(@file_list)]=$file_list2[$i];
	}
}


if ($debug==1) {print join("\n",@file_list); print "\n\n";}

$dbh = fontlinge_Open_Database(
		$config{'username'},
		$config{'password'},
		$config{'mysqlserver'},
		$config{'database'}
	);

if ($insert_into_database==1) {
	if ($keep_database!=1) {
		fontlinge_Clear_Database($dbh);
	}
}

@kategorie	=	fontlinge_Init_Kategories($dbh);
if ( ! defined $file_list[0] ) { print "Nothing to do.\nNo FONT files found in the given directory.\n"; exit; } #Nothing to do. 0 Files.

my	$font;
#foreach $filename (@file_list) {
my $filecount = 0;
for ( ; $filecount < scalar( @file_list ) ; $filecount++ ) {
  $filename = $file_list[ $filecount ];
  fontlinge_Percent( "Done    : " , scalar (@file_list) , $filecount ) if $percent;
  chomp $filename;
  if (-e $filename) {
	fontlinge_Table('-> '.$filename,90);
	if ( $debug==1) { print "\nRead Fontname\n";}
	$font	=	new fontlinge::Fontling();
	if ( ! defined $font->{'complete'} ) {$font->{'complete'}=0; }
	if ( $debug==1) { print "\nRead Fontname done\n";}
	if(  $font->fontlinge_Set_Values($filename) ) {
		@fontnames	=	$font->fontlinge_Get_Names();
		$kategorie_nr	=	fontlinge_Find_Kategorie_Any( $dbh , $font->{'name'} );
		$kategorie		=$kategorie[$kategorie_nr];
		fontlinge_Table( $font->{'name'} ,30 );
		fontlinge_Table($kategorie,10);
		fontlinge_Linebreak();
		if ($kategorie_nr == 0) {
			for( my $i=0; ($i< (@fontnames)) && ($kategorie_nr == 0) ; $i++) {
				$kategorie_nr	=	fontlinge_Find_Kategorie_Any( $dbh , $fontnames[$i]);
				$kategorie		=$kategorie[$kategorie_nr];
				fontlinge_Table(" > ",90);
				fontlinge_Table($fontnames[$i],30);
				fontlinge_Table($kategorie,10);
				fontlinge_Linebreak();
			}
		}
		$just_made_dir="";
		$preview_made=0;


		foreach $filename ( $font->fontlinge_Get_Files() ) {
			if ($filename ne '') {
				($base,$path,$type) = fontlinge_Fileparse($filename);
				$type=lc $type;
				$tmp= $font->{'name'}; $tmp=~s/\n/_/gis; $tmp=~s/\W/_/gis;
				@dest_path	=	fontlinge_Make_Pathname($HOME,$kategorie,$tmp, $font->{'name'} ,$font->{'complete'} , $font);
				$dest_path='';	

					if( $font->{'filetype'} eq "multi") {
						if ($just_made_dir eq '') {
							for ( my $i=0 ; $i<(@dest_path) ; $i++ ) {
								$dest_path.=$dest_path[$i].'/';
							}
							if( $make_dirs !=0 ) {fontlinge_Makedir($dest_path);}
							$newname=$dest_path.$tmp;
							$number="";
							for( my $i=0 ;  -e $newname ; $i++) {
								$number=$i==0?"":"\($i\)";
								$newname=$dest_path.$tmp.$number;
							}
							if( $make_dirs !=0 ) {fontlinge_Makedir($newname);}
							$just_made_dir=$newname;
						} else {
							$newname=$just_made_dir;
						}
						$dest_path="$newname/";
						$newname="$dest_path$tmp$type";
						$number="";
					} else {
						$number=0;
						for ( my $i=0 ; $i<(@dest_path) ; $i++ ) {
							$dest_path.=$dest_path[$i].'/';
						}
						if ( ! -e $dest_path) { 
							if( $make_dirs !=0 ) {
								fontlinge_Makedir($dest_path);
							}
						}
						if( $rename_otf && ($type eq '.ttf') && ($font->{'otf_table'}==1) ) { $type='.otf'; }
						$newname=$dest_path.$tmp.$type;
						for( my $i=2 ;  -e $newname ; $i++) {
								$newname=$dest_path.$tmp."\($i\)$type";
								$number=$i;
						}
					}

				 $font->{'location'} = $filename; # Possibly the font will be copied/moved, then this value will be changed to new location.


				if ($copy == 1) { fontlinge_Copy_File( $filename , $newname ); $font->{'location'}=$newname; }
				if ($move == 1) {	fontlinge_Move_File( $filename , $newname ); $font->{'location'}=$newname; }
				if ($debug == 1) { print "$tmp\n"; }

				if (  ( ($preview_made==0) && ($make_previews==1) )&&
						( ($type eq ".ttf") || ($type eq ".pfa") || ($type eq ".pfb") || ($type eq ".otf") )
					) {
							$font->fontlinge_Create_Image( $force_previews , $debug , $dbh , $my_preview_suffix );
							$preview_made=1;
				}
			}
		}
		if( $copy || $move ) {
			foreach $filename ( $font->fontlinge_Get_More_Files() ) {
					if ($copy == 1) { fontlinge_Copy_More_File( $filename , $dest_path , $number ); }
					if ($move == 1) {	fontlinge_Move_More_File( $filename , $dest_path , $number ); }
			}
		}



		if ($insert_into_database == 1) {
			if( $font->{'filetype'} eq "multi") {
				fontlinge_Insert_Into_Db( $dbh,$path, $font->{'name'} ,$font->{'datatype'},$font->{'filetype'},$kategorie_nr,$font->{'fullinfo'},$font->{'complete'});
			} elsif( $font->{'filetype'} eq "single") {
				fontlinge_Insert_Into_Db( $dbh,$filename, $font->{'name'} ,$font->{'datatype'},$font->{'filetype'},$kategorie_nr,$font->{'fullinfo'},$font->{'complete'});
			} else {
				die "unknown format ".$font->{'filetype'}."\n";
			}
		}



	} else {
		print "Error: Not a font: '$filename' $fontlinge_error\n";
	}
  }
}
if ($percent) {
	fontlinge_Percent( "Done    : " , scalar (@file_list) , $filecount );
	print "\n";
}
fontlinge_Close_Database($dbh);
exit;




sub wanted {
	if (-f && 
(
	/\.afm$/is ||
	/\.ttf$/is ||
	/\.otf$/is ||
	/\.mmm$/is ||
	/\.inf$/is ||
	/\.pfm$/is ||
	/\.pfb$/is ||
	/\.cfg$/is ||
	/\.pfa$/is ||
	/\.png$/is )
	) { $file_list[scalar @file_list]=$File::Find::name;}
}


sub usage {
print	"

fontlinge_base --COMMAND [--OPTION...] folder

--copy                   Copy fontfiles into fontbase
--move                   Move fontfiles into fontbase
                         For --copy and --move:
  --rename-otf           If a ttf contains otf features it will be renamed.
  --fontbase=x           Set a path where you want your fontbase to be
                         created. Defaults to ~/fontbase.

--previews               Generate preview images
  --forcepreviews        Overwrite existing previews
  --my-preview-suffix=x  Some identifier like large,color,... NOT gif,jpg,...

--dbinsert               Build database from fontbase
  --dbkeep               Keep usually outdated database and add entries.

--look                   Just look at files and do nothing. For testing.

Global Options:
  --debug                Lots of debugging output
  --verbose              Verbose status output
  --percent              Show a progress bar
  --my-code=x            Include own perl-code. See manual.

folder                   Contains the fontfiles
fontbase                 ~/fontbase \(see --fontbase\)
";

#  --my-preview=x         Path to own perl-code to generate your previews
#  --my-preview-path=x    Path to own perl-code to generate the path for previews

}


