#!/usr/bin/perl
use strict;
use FileHandle;
use File::Find;
use File::Basename;
use POSIX qw(setlocale);
use Getopt::Long;

my $version = "0.05";
my $search_file_suffix="cfg";
my $start_string="__TCLASS __BGN";
my $end_string="__END";
my $theme_dir = "/usr/share/enlightenment/themes";
my %rewrite_category =
(
    "__NORMAL"                => undef,
    "__NORMAL_ACTIVE"         => undef,
    "__NORMAL_ACTIVE_STICKY"  => undef,
    "__CLICKED"               => undef,
    "__HILITED"               => undef,
);

    my $verbose;
    my $output_lang;
    my $data_dir;
    my $font_data;
    my $tempfile;
    my $dir;
    my $desired_font="-*-helvetica-medium-r-*-*-12-*-*-*-*-*-*-*,-*-fixed-medium-r-normal-*-12-*-*-*-c-*-*-*";
    my $alloverride;
    my $theme_name;
    my $totext;
    my $textflag;
    my $basename;
    my $tempbasename;
    my @cfgfile;
    my @textclass;
    my @fontdata;
    my $datadir = "/usr/share/e18n/";
    # color support
    my $color_support;
my @etheme_suffix = ("\.etheme","\.tar\.gz");
#sub main
{
  &parseopt;                   # get options
  find (\&wanted , "$dir" );   # now @cfgfile containes all cfg files :-)
  if(!@cfgfile)
  {
     &text_print("cannot find cfg file!!\n",2);
     exit;
  }
  foreach (@cfgfile)
  {
    $tempfile = $_;            # if not, $_ changes
    print "tempfile: $_\n" if $verbose;
    &write_file($tempfile) if &search_file($_);
  }
  &text_print("done...\n",1);

  exit;
}






#==================================sub=======================================
sub wanted
{
    push (@cfgfile,"$File::Find::name") if ( ($File::Find::name) =~ /$search_file_suffix$/ );
}
sub search_file
{
    # search_file return 1 if cfgfile contains __TCLASS __BGN
    my $file = FileHandle->new;

    print "search_file: $_\n" if $verbose;
    $file->open($_) || warn "Can't open $_";
    while(<$file>)
     {
        if ( $_ =~ /^$start_string/ ) # __TCLASS __BGN
          {
              $file->close;
              return 1;               # this file contains __TCLASS __BGN
          }
      }
    $file->close;
    return 0;                         # doesn't contains __TCLASS __BGN :-<
}
sub write_file
{
    my $file = FileHandle->new;
    my $outfile = FileHandle->new;
    my $textclass = FileHandle->new;
    my $temp;

           #  /* 1 when between __TCLASS __BGN and __END */
           my $in_search = 0;
           #  /* 1 when in comment */
           my $in_comment = 0;
           my $outputfile = "$tempfile.$output_lang";
                   # ex) /usr/share/enlightenment/Kondara/init.cfg.ja_JP
           my $textfile = "$basename/textclasses.cfg.$output_lang";
                   # ex) /usr/share/enlightenment/Kondara/textclasses.cfg.ja_JP
                   #        $basename contains $dir/$theme_name

    &text_print ("outputfile: $outputfile\n",3) if $verbose;

    if ($totext)   # when --totext enabled
    {
        &textclasses_init if (!$textflag); # initialize
                                           # if ($textflag) then already done.
        if ( $outputfile eq $textfile )
         {
            # oh! $outputfile contains "textclasses.cfg.$output_lang"
            print "return because $outputfile eq $textfile";
            return;
         }
    }
    $file->open($tempfile) || warn "Can't open $tempfile";

    # if --totext enabled, don't needed actions below
    #goto WRITE if ($totext);

    if ( -f $outputfile )
      {
         if ($alloverride)  # true => all cfg.$output_lang overrided
           {
             $outfile->open(">$outputfile") || warn "Can't open $outputfile";
             goto WRITE;
           }
         &text_print ("$outputfile exsists, override it? [Y/n/a]",3);
         my $tempgetc;
         while ( $tempgetc = <STDIN> )
         {
            if( lc($tempgetc) =~  /n/ )
              {
                 &text_print ("not override\n",1);
                 return;

              }else{
                 $alloverride = 1 if (lc($tempgetc) =~ /a/);
                 $outfile->open(">$outputfile") || warn "Can't open $outputfile";
                 last;
              }
          }
      }
     else
      {
              $outfile->open(">$outputfile") || warn "Can't open $outputfile";
      }

WRITE:
    $textclass->open(">>$textfile") if ($totext);
    while(<$file>)
     {
        $in_search = 1 if ( $_ =~ /^$start_string/ ); # now in __TCLASS __BEGIN
        $in_comment = 1 if ($_ =~ /\/\*/ );             # now in comment
        my $temflag = 0;
        if($in_search)
          {

              foreach $temp (keys %rewrite_category)
                {
                   if ($_ =~ m|$temp |)
                     {
                        &text_print ("find $temp\n",3) if $verbose;
                        &text_print ("change to $rewrite_category{$temp}\n",1) if $verbose;
                        if($totext)
                        {
                          if(!$in_comment){
                              print $textclass "  $temp \"$rewrite_category{$temp}\"\n";
                          }else{
                              print $textclass $_;
                          }
                        }else{
                          if(!$in_comment){
                              print $outfile "  $temp \"$rewrite_category{$temp}\"\n";
                          }else{
                              print $outfile $_;
                          }
                        }
                        $temflag = 1;
                     }
                 }
              if ($totext){
                print $textclass $_ if $temflag == 0;
              }else{
                print $outfile $_ if $temflag == 0;
              }
              # now go outside from __TCLASS __BEGIN
              $in_search = 0 if ( $_ =~ /^$end_string/ );
              $in_comment = 0 if ( $_ =~ /\*\// );
          }
          else{
              print $outfile $_;
              $in_comment = 0 if ( $_ =~ /\*\// );
          }
     }
    $file->close;
    $outfile->close;
    $textclass->close;

}
sub parseopt
{
    no strict;

    GetOptions(
               "locale=s", # set locale (use output_suffix
               "fonts:s",  # set fonts
               "dir=s",    # set directory for search
               "theme:s",  # theme name
               "install=s",# install etheme
               "v",        # verbose mode
               "color",    # color mode
               "help",     # help mode
               "version",  # show version
               "copyright",# show copyright
	       "totext",   # use textclasses.cfg
    );

    if($opt_help){    print <<"EOF";
e18n version $version

usage: e18n [ --locale locale ] [ --dir dir ] [ --theme theme <--totext> ]
              [ --install etheme ] [ --totext ] [ --version ]
	        [ --copyright ] [ -v ] [ --color ]

  --locale  locale :  use this locale instead of
                      string returned by setlocale(LC_MESSAGES,NULL)
  --dir     dir    :  set this directory to be searched
  --theme   theme  :  theme name to be translated
     --totext      :  if this option added , all font setting are written
                      to textclasses.cfg.<locale>
  --install etheme :  install etheme before translating
  --color          :  display messages with color
  --version        :  show version
  --help           :  show this message
  --copyright      :  show copyright
  -v               :  verbose mode

EOF
        exit;
    }
    # show copyright
    if($opt_copyright)
      {
          &show_copyright;
          exit;
      }
    # show version
    print "$version\n" if $opt_version;
    exit if $opt_version;
    $verbose = $opt_v;
    # color_support = 1 if --color
    if($opt_color)
     {
        $color_support = 1;
        &text_print("checking whether color support is enabled...");
        &text_print("  [ Yes ]\n",1);
     }else{
        &text_print("checking whether color support is enabled...");
        &text_print("  [ No ]\n");
     }
    # locale
    &text_print("\nchecking what locale is used...\n\n",3);
    &text_print("whether you define locale with --locale...",6);
    if(!$opt_locale)
     {
        &text_print(" [ No ]\n",3);
        $output_lang = POSIX::setlocale(LC_MESSAGES,"");
        &text_print("checking setlocale(LC_MESSAGES,NULL) returns... ",6);
        &text_print("[ $output_lang ]\n",1);
        &text_print("\nusing locale ",6);
        &text_print("[ $output_lang ]\n",5);
     }
      else
     {
        &text_print(" [ Yes ]\n",1);
        $output_lang = $opt_locale;
        &text_print("now using locale...",6);
        &text_print(" [ $output_lang ]\n",1);
     }
    # search dir
    sleep(1);
    &text_print("\nchecking search directory...\n\n",3);
    &text_print("whether you define search directory with --dir...",6);
    if(!$opt_dir)
     {
       &text_print(" [ No ]\n",3);
       &text_print("checking wehther you can write $theme_dir...",6);
       if(-w $theme_dir){
          &text_print(" [ Yes ]\n",1);
          $dir = $theme_dir;
          &text_print("\nusing dir...",6);
          &text_print(" [ $dir ]\n",5);
       }
       else{
          &text_print(" [ No ]\n",3);
          $dir = "$ENV{'HOME'}/.enlightenment/themes";
          &text_print("checking wether you can write $dir...",6);
	  if (-w $dir){
              &text_print(" [ Yes ]\n",1);
              &text_print("\nusing dir",6);
              &text_print(" [ $dir ]\n",5);

#             &text_print("Warning: cannot write to $theme_dir\nusing $dir\n",3);
          }
	  else{
	     &text_print("Error: Oops I cannot write $dir\n",2);
	     &text_print("Error: Please use --dir option\n",2);
	     exit;
	  }
       }
#       &text_print ("Message: dir not defined. using $dir\n",3) if $verbose;
     }
      else{
       $dir = $opt_dir;
       &text_print(" [ Yes ]\n",1);
       &text_print("checking wether you can write $dir...",6);
       if(-w $dir){
             &text_print(" [ Yes ]\n",1);
             &text_print("now using dir",6);
             &text_print(" [ $dir ]\n",5);
       }else{
            &text_print(" [ No ]\n",2);
            &text_print("Error: Oops I cannot write $dir\n",2);
            &text_print("Error: please check $dir\n",2);
            exit;
      }
#       &text_print ("Message: dir defined. using $dir\n",3) if $verbose;
     }
    # install etheme
    sleep(1);
    &text_print("\nchecking whether you want to install etheme\n\n",3);
    &text_print("whether you define etheme with --install...",6);
    if($opt_install)
    {
        &text_print(" [ Yes ]\n",1);
        ($opt_theme,$name,$suffix) = File::Basename::fileparse("$opt_install",@etheme_suffix);
        &text_print("checking whether $opt_install looks like Etheme...",6);
        if($suffix ne '.etheme' && $suffix ne '.tar.gz')
	{
           &text_print(" [ No ]\n",2);
	   &text_print ("Error: $opt_install doesn't look like Etheme\n",2);
	   exit;
	}
#        &text_print(" [ Yes ]\n",1);
	&etheme_install($opt_install,$opt_theme);
    }else{
        &text_print(" [ No ]\n",3);
    }
    # theme_name
    sleep(1);
    &text_print("\nchecking theme name\n\n",3);
    &text_print("whether you define theme name with --theme...",6);
    if($opt_theme)
    {
       $theme_name = $opt_theme;
       &text_print(" [ Yes ]\n",1);
       &text_print("cheking whether $dir/$theme_name exsits...",6);
       if(! -d "$dir/$theme_name")
       {
          &text_print(" [ No ]\n",2);
          &text_print("Error: cannot find $dir/$theme_name\n",2);
	  exit;
       }
       &text_print(" [ Yes ]\n",1);
       &text_print("\ntheme name for translating",6);
       &text_print(" [ $theme_name ]\n",5);
    }else{
       &text_print(" [ No ]\n",3);
    }
    # use textclasses.cfg
    sleep(1);
    &text_print("\nchecking whether all font setting use textclasses.cfg\n",3);
    &text_print("\nwhether you define to use textclasses.cfg with --totext...",6);
    if($opt_totext)
    {
        &text_print(" [ Yes ]\n",1);
        &text_print("checking whether you define theme name...",6);
        if($opt_theme){
           &text_print(" [ Yes ]\n",1);
           $opt_totext="yes";
	   $totext = "yes";
        }
        else{
           &text_print(" [ No ]\n",2);
	   &text_print("Error: detect --totext option but not define --theme <theme>\n",2);
	   exit;
        }
    }else{
        $opt_totext="no";
        &text_print(" [ No ]\n",3);
    }
    # font setting
    sleep(1);
    if(!$opt_font)
     {
        &text_print (qq|\nsearching font setting... \n\n|,3);
	&search_font;

     }else{

        &text_print ("Message: font defined. using $opt_font\n",3) if $verbose;
        $desired_font = $opt_font;
        &text_ptinr ("Error: this option is obsolete\n",2);
     }

sleep(1);
#SEARCH:

&text_print("--------------------------------------------------------\n",6);
&text_print("                   SETTING INFOMATION\n",6);
&text_print("--------------------------------------------------------\n",6);
&text_print("translated locale    =>",6);
&text_print(" [ $output_lang ]\n",5);
&text_print("use textclasses.cfg  =>",6);
&text_print(" [ $opt_totext ]\n",5);
&text_print("theme name           =>",6);
&text_print(" [ $theme_name ]\n",5);
&text_print("top directory\n  =>",6);
&text_print(" [ $dir ]\n",5);
&text_print("font\n",6);
&text_print("  __NORMAL\n",3);
&text_print("  =>",6);
&text_print(" [ $rewrite_category{\"__NORMAL\"} ]\n",5);
&text_print("  __NORMAL_ACTIVE\n",3);
&text_print("  =>",6);
&text_print(" [ $rewrite_category{\"__NORMAL_ACTIVE\"} ]\n",5);
&text_print("  __NORMAL_ACTIVE_STICKY\n",3);
&text_print("  =>",6);
&text_print(" [ $rewrite_category{\"__NORMAL_ACTIVE_STICKY\"} ]\n",5);
&text_print("  __CLICKED\n",3);
&text_print("  =>",6);
&text_print(" [ $rewrite_category{\"__CLICKED\"} ]\n",5);
&text_print("  __HILITED\n",3);
&text_print("  =>",6);
&text_print(" [ $rewrite_category{\"__HILITED\"} ]\n",5);
&text_print("--------------------------------------------------------\n",6);

    print "                               now translating...\n";
    print "                                          OK? [Y/n]";
    while ( <STDIN> )
    {
        exit if ( lc($_) =~ /n/);
        last;
    }
    $dir = "$dir/$theme_name";
    $basename = $dir;
    sleep(2);
    use strict;
}
sub textclasses_init
{
    my $isexsist;

    if(! -f "$basename/textclasses.cfg") # textclasses.cfg doesn't exsist.
     {
         &text_print ("\n$basename/textclasses.cfg doesn't exsists\n\n",3);
         &text_print ("OK! add",6);
         &text_print (" [ ",3);
         &text_print ("#include <definitions>",1);
         &text_print (" ] ",3);
         &text_print ("\n to ",6);
         &text_print ("[ $basename/textclasses.cfg.$output_lang ]\n\n",5);
         my $textfile = new FileHandle;
         $textfile->open(">$basename/textclasses.cfg.$output_lang");
         # needed
         print $textfile "#include <definitions>\n";
         $textfile->close;
         $textflag = 1;   # initialize done
         return;
     }
    if(!$textflag)
     {
         my $file = new FileHandle;
         my $textfile = new FileHandle;
         $file->open("$basename/textclasses.cfg") || warn "Can't open";
         $textfile->open(">$basename/textclasses.cfg.$output_lang") || warn "Can't open";
         my $in_search = 0;
         my $in_comment = 0;
         my $temp;
         while(<$file>)
          {
             $in_search = 1 if ( $_ =~ /^$start_string/ );
             $in_comment = 1 if ( $_ =~ /\/\*/ );
             my $temflag = 0;
             if($in_search)
               {
		   if(!$in_comment){
                        foreach $temp (keys %rewrite_category)
                          {
                             if ($_ =~ m|$temp |)
                               {
                                  print "find $temp\n" if $verbose;
                                  print "change to $desired_font\n" if $verbose;
                                  print $textfile "  $temp \"$desired_font\"\n";
                                  $temflag = 1;
                               }
                           }
                        print $textfile $_ if $temflag == 0;
                        $in_search = 0 if ( $_ =~ /^$end_string/ );

                   }else{
                          print $textfile $_;
                          $in_comment = 0 if ( $_ =~ /\*\// );
                          $in_search = 0 if ($_ =~ /^$end_string/ );
                   }
               }else{
                  $in_comment = 0 if ( $_ =~ /\*\// );
                  print $textfile $_;
               }

          }
          $textfile->close;
          $textflag = 1;        # initialize done
    }
}
sub show_copyright
{
print <<"EOF";
====================================================================
  Enlightenment Theme I18N Helper  version $version
====================================================================

Copyright: 2000 (c) Motonobu Ichimura <famao\@kondara.org>

--------------------------------------------------------------------
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
--------------------------------------------------------------------
EOF
}
sub text_print
{
    my @color = (
            "",             # not defined
            q|\\033[1;32m|, # green
            q|\\033[1;31m|, # red
            q|\\033[1;33m|, # yellow
            q|\\033[1;34m|, # blue
            q|\\033[1;36m|, # cyan
            q|\\033[1;01m|, # blink
    );
#    my $col_num = 60;
#    my $color_col = "\\\\033[$col_num","G";
    my $color_normal;
    my $text = shift; # text for display
    my $color = shift; # 1 green 2 red 3 yellow
#    my $show = shift; # use color or not if $color_support is true
    $color_normal = q|\\033[1;00m| if ($color);
    if ( $color_support )
     {
         # show color test
         system(qq|echo -en "$color[$color]$text$color_normal"|);
#         system("echo");

     }else{
         print "$text";
     }
}
sub etheme_install
{
     my $etheme = shift;
     my $name = shift;

     if ( -r $etheme )
     {
        &text_print(" [ Yes ]\n",1);
        if(!mkdir("$dir/$name",0755))
	{
            &text_print("Error: cannot make directory $dir/$name\n",2);
	    exit;
	}
	system("tar xvfz $etheme -C $dir/$name");
     }else{
        &text_print(" [ No ]\n",2);
        &text_print("Error: cannot read $etheme\n",2);
        exit;
     }
}
sub search_font
{
    my $eachfontflag = 0;
    my @category;
    my $datafile;
    &text_print("checking locale $output_lang has font data...",6);
    if (-r "$output_lang/fontdata")
    {
        $datafile = "$output_lang/fontdata";
    }
    else
     {
        if(! -r "$datadir/$output_lang/fontdata")
	{

        	&text_print(" [ No ]\n\n",2);
        	&text_print("Error: cannot access $output_lang/fontdata\n",2);
        	&text_print("Error: cannot find font database\n",2);
        	exit;
    	}else{
	        $datafile = "$datadir/$output_lang/fontdata";
	}
    }
    &text_print(" [ Yes ]\n\n",1);
    my $fontfile = FileHandle->new;
    my $in_fontinfo = 0;
    $fontfile->open("$datafile");
    while(<$fontfile>)
     {
       chop($_);
       $in_fontinfo = 1 if $_ eq "[font]";
       if($in_fontinfo)
        {
           $in_fontinfo = 0;
           push(@fontdata,$fontfile->getline);
           push(@fontdata,$fontfile->getline);
           push(@fontdata,$fontfile->getline);

	 }

      }
    $fontfile->close();
    if(! @fontdata )
    {
        &text_print("Error: cannot find font\n",2);
	exit;
    }
    my $loop = int($#fontdata/3);
    my $label = $loop+1;
    &text_print("\nlocale $output_lang has $label fontdata\n",3);
    chop(@fontdata);

SEARCH:
    my $num = 0;
    foreach(0..$loop)
    {
#        print &text_print(<<"EOF",1);

         &text_print("FONT[$_]\n\n",5);
         &text_print("-------------------------------\n");
         &text_print("font   : ",6);
         &text_print("[$fontdata[$num]]\n",1);
         &text_print("size   : ",6);
         &text_print("[$fontdata[$num+1]]\n",1);
         &text_print("comment: ",6);
         &text_print("[$fontdata[$num+2]]\n\n",1);

         $num += 3;
    }

DEFINE_FONT:
    &text_print ("\nwhich font do you want to use? [num](0-$loop)",6);
    while(my $getc = <STDIN>)
    {
        if( int($getc) > $loop || int($getc) < 0)
	{
	   &text_print ("\nno such fonts!!\n",3);
	   goto DEFINE_FONT;

        }else{
           &text_print ("do you want to set all font categores such as __NORMAL to this font? [Y/n]",3) if (!$eachfontflag);
           &text_print ("press any key",3) if ($eachfontflag);
	   while( my $yesno = <STDIN> )
	   {
	        if(lc($yesno) =~ /n/ || $eachfontflag)
		{
		    &text_print("Fmmm.. OK! now you can set font for each category\n",3) if (!$eachfontflag);
                    if (!$eachfontflag)
                    {
                        foreach(keys %rewrite_category)
                        {
                             push(@category,"$_");
                        }
                        @category = sort(@category);
                        $eachfontflag = 1;
                    }
                    &text_print("which category do you want to set to this font?\n\n",3);
                    foreach(0..$#category)
                    {
                        my $tempcolor;
                        if(defined $rewrite_category{$category[$_]})
                        {
                             $tempcolor = 3;
                        }else{
                             $tempcolor = 0;
                        }
                        &text_print("[$_] $category[$_]\n",$tempcolor);
                    }
                    print "\n[num]";
                    while ( my $tempkey = <STDIN> )
                    {
                        if(defined $category[int($tempkey)])
                        {
                              $rewrite_category{$category[int($tempkey)]} = $fontdata[$getc*3];
                              &text_print ("\nfont for ");
                              &text_print ("[ ",6);
                              &text_print ("$category[int($tempkey)]",3);
                              &text_print (" ]",6);
                              &text_print (" is set to\n\n=>");
                              &text_print ("[ ",6);
                              &text_print ("$fontdata[$getc*3]",1);
                              &text_print (" ]\n\n",6);
                              last;
                        }
                        goto SEARCH;
                    }
                    foreach( keys %rewrite_category )
                    {
                        goto SEARCH if (!defined $rewrite_category{$_});
                    }
                    &text_print("font setting is finished\n\n",6);
                    last;
		}
		foreach(keys %rewrite_category)
		{
                     my $fontnum = $getc * 3;
		     $rewrite_category{$_} = $fontdata[$fontnum];
		     &text_print ("font for ");
                     &text_print ("[ ",6);
                     &text_print ("$_",3);
                     &text_print (" ]",6);
                     &text_print (" category is set to\n\n=>");
                     &text_print ("[ ",6);
                     &text_print ("$fontdata[$fontnum]",1);
                     &text_print (" ]\n\n",6);

		}
                &text_print("font setting is finished\n\n",6);
		last;
	   }
	   last;
	}
    }
#    exit;
    return;
}
