# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
use strict;
use warnings;

use AgentConfig;
use Logging;

package IDN;

# on failure function returns domain passed
sub idnToUtf8 {
  my ($idnDomain) = @_;

  my $idnconvBin = AgentConfig::idnconvBin();

  unless ($idnconvBin) {
    return $idnDomain;
  }

  my $converted = `echo '$idnDomain' | $idnconvBin -reverse -out 'UTF-8'`;
  chomp $converted;

  unless ($converted) {
    Logging::warning("Failed to convert domain '$idnDomain' to UTF-8.");
    return $idnDomain;
  }

  return $converted;
}

# on failure function returns domain passed
sub utf8ToIdn {
  my ($utf8domain) = @_;

  my $idnconvBin = AgentConfig::idnconvBin();

  unless ($idnconvBin) {
    return $utf8domain;
  }

  my $converted = `echo '$utf8domain' | $idnconvBin -in 'UTF-8'`;
  chomp $converted;

  unless ($converted) {
    Logging::warning("Failed to convert domain '$utf8domain' from UTF-8.");
    return $utf8domain;
  }

  return $converted;
}

sub isIdnDomain {
  my ($domain) = @_;

  # IDN domain has some part in punycode, it is a first part (^) or any other (after ".") 
  return $domain =~ /(^|\.)xn--/;
}

sub canConvert {
  if (AgentConfig::idnconvBin()) {
    return (1, '');
  } else {
    return (0, "can't find idnconv binary");
  }
}

1;
