#!/usr/bin/perl

########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####

use IPC::Open2;
use IO::Handle;

$idn_shell = '/usr/local/bin/idnconv';
$idn_vendor = 'idnkit';
$iconv_shell = '/usr/bin/iconv';
$iconv_utf8 = '';

if (scalar(@ARGV) < 1) {
  print STDERR "Usage: idn_transform.pl <charset> <string>\n";
  exit 0;
}

unless ($idn_shell && -x $idn_shell) {
  print STDOUT "error: IDN transformation toolkit (idnkit software) probably is not installed on the machine. Contact your server administrator for support.\n";
  exit 1;
}

my $charset = $ARGV[0];
my $nat_str = $ARGV[1];

my $href_res = &idnEncode({1 => $nat_str}, $idn_shell, $idn_vendor, $charset);
print STDOUT "to_idn: ".$$href_res{1}."\n";

sub idnCheckVendor {
  my $idn_shell=shift;
  my $vendor;
  if (-x $idn_shell){
    my $out;
    foreach $key ('v','V'){
      $out=`$idn_shell -$key 2>&1`;
      if ($out=~/invalid|usage/i){
	next;
      }
      if( $out=~/^(\w+)\s*\(\s*(\w+)\s*\)/ ){
	$vendor=$2;
	last;
      }
    }
  }
  return $vendor;
}

sub idnEncode {
  my $src = shift;
  my $shell = shift || $idn_shell;
  my $vendor = shift || $idn_vendor;
  my $charset = shift || $iconv_utf8;
  
  unless (-x $shell) {
    return;
  }

  my $ref=ref($src);
  my $values='';
  my @keys=();
  if ( $ref eq 'HASH'){
    while ( my($key,$value)=each(%$src)){
      $values .= "$value\n";
      push @keys,$key;
    }
  }
  elsif( $ref eq 'ARRAY'){
    $values = join("\n",@$src);
  }
  else {
    $values = $src;
  }
  unless ($vendor){
    $vendor = $idn_vendor = &idnCheckVendor($shell);
  }
  my $args='';
  if ($vendor eq 'libidn'){
    $args='-l -a --quiet';
    unless ($charset =~ /UTF-?8/i ){
      if (-x $iconv_shell){
				$shell="$iconv_shell -f $charset -t $iconv_utf8 | $shell";
      }
    }
  }
  elsif($vendor eq 'idnkit') {
    $args="-i $charset";
  }

  my ($reader,$writer)=(IO::Handle->new,IO::Handle->new);
  eval {
    $cmd="$shell $args";
    open2($reader, $writer, $cmd);
  };
  if ($@){
    if ($@ =~ /~open2/){
      return;
    }
    die;
  }
  $writer->print($values);
  $writer->close;

  
  my @res=(),$line;
  while ($line=$reader->getline){
    chomp $line;
    push @res, $line;
  }

  $reader->close;

  if ( $ref eq 'HASH'){
    if (scalar(@res)==scalar(@keys) ){
      my %ret;

      for (my $i=0; $i<= $#keys; $i++){
	$ret{$keys[$i]}=$res[$i];
      }

      return \%ret;
    }
  }
  elsif($ref eq 'ARRAY'){
    if (scalar(@res)==scalar(@{$src})){
      return \@res;
    }
  }else{
    return join('',@res);
  }
}

exit 0;
