#!%PERL% -w
# Copyright (c) vhffs project and its contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions 
# are met:
#
# 1. Redistributions of source code must retain the above copyright 
#   notice, this list of conditions and the following disclaimer.
#2. Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in 
#   the documentation and/or other materials provided with the 
#   distribution.
#3. Neither the name of vhffs nor the names of its contributors 
#   may be used to endorse or promote products derived from this 
#   software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
#"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 
#COPYRIGHT OWNER OR CONTRIBUTORS 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.


use utf8;
use POSIX qw(locale_h);
use HTML::Template;
use locale;
use Locale::gettext;
use CGI;
use CGI::Session;
use strict;


use lib '%VHFFS_LIB_DIR%';
use Vhffs::User;
use Vhffs::Group;
use Vhffs::Main;
use Vhffs::Panel::Main;
use Vhffs::Panel::Menu;
use Vhffs::Panel::Object;


my $panel = new Vhffs::Panel::Main();
exit 0 unless $panel;
my $session = $panel->get_session;
exit 0 unless $session;

my $vhffs = $panel->{'vhffs'};
my $templatedir = $panel->{'templatedir'};
my $user = $panel->{'user'};
my $cgi = $panel->{'cgi'};

my $domain_name = $cgi->param('domain');
# FIXME Temporary hack to be compatible with project info page
$domain_name = $cgi->param('name') unless(defined $domain_name);

my $dns = Vhffs::Services::DNS::get_by_domainname( $vhffs , $domain_name );

my $thirdtemplate;
my $template;
my $output = "";
my $message;

unless( defined $domain_name )
{
	$template = new HTML::Template( filename => $templatedir.'/panel/misc/simplemsg.tmpl' );
	$template->param( MESSAGE => gettext( 'CGI Error !' ) );
}
elsif( ! defined $dns )
{
	$template = new HTML::Template( filename => $templatedir.'/panel/misc/simplemsg.tmpl' );
	$template->param( MESSAGE => gettext('Cannot get informations on this object') );
}
elsif( ! $user->can_view( $dns ) )
{
	$template = new HTML::Template( filename => $templatedir.'/panel/misc/simplemsg.tmpl' );
	$template->param( MESSAGE => gettext( 'You\'re not allowed to do this, object is not in active state or you don\'t have enough ACL rights' ) );
}
else
{
    my $action = $cgi->param('action');
ACTION: {
    if(defined $action) {
        # Check user's rights
        unless( $user->can_modify( $dns ) ) {
            $panel->add_error( gettext( 'You\'re not allowed to do this, object is not in active state or you don\'t have enough ACL rights' ) );
            last ACTION;
        }
        my $id = $cgi->param('rr_id');
        my $data = $cgi->param('data');
        my $name = $cgi->param('name');
        my $aux = $cgi->param('aux');

        if($action eq 'manage_a') {
            if(defined $cgi->param('modify_a_submit')) {
                # User just want to modify an A record
                eval { Vhffs::Panel::DNS::update_a($dns, $id, $data); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to modify A record: %s'), $@)); }
                else { $panel->add_info(gettext('A Record updated')); }
            } else {
                # User wants to delete it
                eval { Vhffs::Panel::DNS::delete_record($dns, $id, 'A'); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to delete A record: %s'), $@)); }
                else { $panel->add_info(gettext('A Record deleted')); }
            }
        } elsif($action eq 'manage_aaaa') {
            if(defined $cgi->param('modify_aaaa_submit')) {
                # User just want to modify an AAAA record
                eval { Vhffs::Panel::DNS::update_aaaa($dns, $id, $data); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to modify AAAA record: %s'), $@)); }
                else { $panel->add_info(gettext('AAAA Record updated')); }
            } else {
                # User wants to delete it
                eval { Vhffs::Panel::DNS::delete_record($dns, $id, 'AAAA'); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to delete AAAA record: %s'), $@)); }
                else { $panel->add_info(gettext('AAAA Record deleted')); }
            }
        } elsif($action eq 'add_aaaa') {
            my $redirect = $cgi->param('redirect');
            eval { Vhffs::Panel::DNS::add_aaaa($dns, (defined $redirect && $redirect eq 'true'), $name, $data); };
            if($@) { $panel->add_error(sprintf(gettext('Unable to add AAAA record: %s'), $@)); }
            else { $panel->add_info(gettext('AAAA record added')); }
        } elsif($action eq 'add_a') {
            my $redirect = $cgi->param('redirect');
            eval { Vhffs::Panel::DNS::add_a($dns, (defined $redirect && $redirect eq 'true'), $name, $data); };
            if($@) { $panel->add_error(sprintf(gettext('Unable to add A record: %s'), $@)); }
            else { $panel->add_info(gettext('A record added')); }
        } elsif($action eq 'manage_mx') {
            if(defined $cgi->param('modify_mx_submit')) {
                # User wants to modify an MX record
                eval { Vhffs::Panel::DNS::update_mx($dns, $id, $data); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to modify MX record: %s'), $@)); }
                else { $panel->add_info(gettext('MX Record updated')); }
            } else {
                # MX deletion
                eval { Vhffs::Panel::DNS::delete_record($dns, $id, 'MX'); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to delete MX record: %s'), $@)); }
                else { $panel->add_info(gettext('MX Record deleted')); }
            }
        } elsif($action eq 'add_mx') {
            eval { Vhffs::Panel::DNS::add_mx($dns, $name, $data, $aux); };
            if($@) { $panel->add_error(sprintf(gettext('Unable to add MX record: %s'), $@)); }
            else { $panel->add_info(gettext('MX Record added')); }
        } elsif($action eq 'manage_ns') {
            # Only deletion is allowed for NS record
            eval { Vhffs::Panel::DNS::delete_record($dns, $id, 'NS'); };
            if($@) { $panel->add_error(sprintf(gettext('Unable to delete NS record: %s'), $@)); }
            else { $panel->add_info(gettext('NS Record deleted')); }
        } elsif($action eq 'add_ns') {
            eval { Vhffs::Panel::DNS::add_ns($dns, $name, $data); };
            if($@) { $panel->add_error(sprintf(gettext('Unable to add NS record: %s'), $@)); }
            else { $panel->add_info(gettext('NS Record added')); }
        } elsif($action eq 'manage_cname') {
            if(defined $cgi->param('modify_cname_submit')) {
                eval { Vhffs::Panel::DNS::update_cname($dns, $id, $data); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to modify CNAME record: %s'), $@)); }
                else { $panel->add_info(gettext('CNAME Record updated')); }
            } else {
                eval { Vhffs::Panel::DNS::delete_record($dns, $id, 'CNAME'); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to delete CNAME record: %s'), $@)); }
                else { $panel->add_info(gettext('CNAME Record deleted')); }
            }
        } elsif($action eq 'add_cname') {
            eval { Vhffs::Panel::DNS::add_cname($dns, $name, $data); };
            if($@) { $panel->add_error(sprintf(gettext('Unable to add CNAME record: %s'), $@)); }
            else { $panel->add_info(gettext('CNAME Record added')); }
        } elsif($action eq 'manage_srv') {
            if(defined $cgi->param('modify_srv_submit')) {
                my $host = $cgi->param('host');
                my $port = $cgi->param('port');
                my $weight = $cgi->param('weight');
                eval { Vhffs::Panel::DNS::update_srv($dns, $id, $host, $port, $aux, $weight); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to modify SRV record: %s'), $@)); }
                else { $panel->add_info(gettext('SRV Record updated')); }
            } else {
                eval { Vhffs::Panel::DNS::delete_record($dns, $id, 'SRV'); };
                 if($@) { $panel->add_error(sprintf(gettext('Unable to delete SRV record: %s'), $@)); }
                 else { $panel->add_info(gettext('SRV Record deleted')); }
            }
        }elsif($action eq 'add_srv') {
            my $proto = $cgi->param('protocol');
            my $svc = $cgi->param('service');
            my $host = $cgi->param('host');
            my $port = $cgi->param('port');
            my $aux = $cgi->param('aux');
            my $weight = $cgi->param('weight');
            eval { Vhffs::Panel::DNS::add_srv($dns, $name, $proto, $svc, $host, $port, $aux, $weight); };
            if($@) { $panel->add_error(sprintf(gettext('Unable to add SRV record: %s'), $@)); }
            else { $panel->add_info(gettext('SRV Record added')); }
        } elsif($action eq 'add_txt') {
            eval { Vhffs::Panel::DNS::add_txt($dns, $name, $data); };
            if($@) { $panel->add_error(sprintf(gettext('Unable to add TXT record: %s'), $@)); }
            else { $panel->add_info(gettext('TXT Record added')); }
        } elsif($action eq 'manage_txt') {
            if(defined $cgi->param('modify_txt_submit')) {
                # User wants to modify an TXT record
                eval { Vhffs::Panel::DNS::update_txt($dns, $id, $data); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to modify TXT record: %s'), $@)); }
                else { $panel->add_info(gettext('TXT Record updated')); }
            } else {
                # TXT deletion
                eval { Vhffs::Panel::DNS::delete_record($dns, $id, 'TXT'); };
                if($@) { $panel->add_error(sprintf(gettext('Unable to delete TXT record: %s'), $@)); }
                else { $panel->add_info(gettext('TXT Record deleted')); }
            }
        }
    }
}
	my $cnames = $dns->get_cname_type;
	my $a_rr = $dns->get_a_type;
    my $aaaa = $dns->get_aaaa_type;
	my $mx = $dns->get_mx_type;
	my $ns = $dns->get_ns_type;
    my $srv = $dns->get_srv_type;
    my $txt = $dns->get_txt_type;

    $panel->set_title(sprintf(gettext("DNS Administration - %s"), $domain_name));
	$template = new HTML::Template( filename => $templatedir."/panel/dns/prefs.tmpl" );

    $template->param( DOMAIN_NAME => $domain_name );

    $template->param( TEXT_TYPEA => gettext('All A TYPE for your domain name') );
    $template->param( TEXT_TYPEAAAA => gettext('All AAAA TYPE for your domain name') );
    $template->param( TEXT_TYPEMX => gettext('All MX TYPE for your domain name') );
    $template->param( TEXT_TYPECNAME => gettext('All CNAME for your domain name') );
    $template->param( TEXT_LIST_A => gettext("List all A reccords") );
    $template->param( TEXT_LIST_AAAA => gettext("List all AAAA reccords") );
    $template->param( TEXT_ADD_A => gettext("Add an A record") );
    $template->param( TEXT_ADD_AAAA => gettext("Add an AAAA record") );
    $template->param( TEXT_ORIGIN => sprintf( gettext('Use @ for origin (%s)'),  $domain_name) );


	#Treat ACL part
    $template->param( VALUE_OID => $dns->get_oid );
    $template->param( TEXT_ACL_ADMIN => gettext( "Admin Rights on this object (ACL)") );
    $template->param( EXPLAIN_ADMIN_ACL => gettext( "You can Manage rights on this service for each user in the VHFFS database. Please read help before manage it.") );
    $template->param( ADMIN_ACL => gettext("Ok, go to ACL admin") );


	#Treat the delete part
	$template->param( TEXT_DELETE_DNS => gettext("Delete this domain name from the VHFFS platform") );
	$template->param( TEXT_BEFORE_DELETE => gettext("This action is non-reversible. This domain name will be DESTROYED.") );
	$template->param( ASK_DELETE_DNS => gettext("Are you SURE you want DELETE this domain ?") );
	$template->param( YES => gettext("Yes I'm sure of what I do") );
	$template->param( NO => gettext("No, I'm not sure, I prefer to keep it.") );
	$template->param( TEXT_DELETE => gettext("Delete") );


	#All templates values for A reccords
    $template->param( TEXT_QUESTION_REDIRECTION => gettext("Use our servers as destination IP for this A record?") );
    $template->param( TEXT_YES => gettext("Yes") );
    $template->param( TEXT_NO => gettext("No") );
    $template->param( TEXT_ADDIP => gettext("IP") );
    $template->param( TEXT_DOMAINNAME => gettext("Name for reccord") );
    $template->param( TEXT_SUBMIT => gettext("Add !") );


	#All templates for MX reccords
    $template->param( TEXT_LIST_MX => gettext("All MX TYPE for your domain name") );
    $template->param( TEXT_ADD_MX => gettext("Add a MX field to your domain") );
    $template->param( MX_DOMAINNAME => gettext("Name of the record") );
    $template->param( MX_NAME => gettext("Name of your MX") );
    $template->param( MX_PRIORITY => gettext("Priority of your MX") );
    $template->param( TEXT_SUBMIT => gettext("Submit") );


	#Treat CNAME PART
    $template->param( TEXT_LIST_CNAME => gettext("All CNAME TYPE for your domain name") );
    $template->param( TEXT_ADD_CNAME => gettext("Add a CNAME field to your domain") );
    $template->param( TEXT_SUBMIT => gettext("Submit") );
    $template->param( CNAME_DESTINATION => gettext("Destination") );
    $template->param( CNAME_PREFIX => gettext("Subdomain name") );

	#Treat NS part
    $template->param( TEXT_TYPENS => gettext("NS TYPE") );
    $template->param( TEXT_LIST_NS => gettext("All NS TYPE for your domain name") );
    $template->param( TEXT_ADD_NS => gettext("Add a NS field to your domain") );
    $template->param( NS_PREFIX => gettext('Name of the record') );
    $template->param( NS_HOSTNAME_TEXT => gettext('Host of your name server') );

    #Treat SRV part
    $template->param( TEXT_TYPESRV => gettext('SRV TYPE') );
    $template->param( TEXT_LIST_SRV => gettext('All SRV records for your domain name') );
    $template->param( TEXT_ADD_SRV => gettext('Add a SRV record to your domain') );
    $template->param( SRV_PREFIX => gettext('Name of the record') );
    $template->param( SRV_PROTOCOL_TEXT => gettext('Protocol') );
    $template->param( SRV_SERVICE_TEXT => gettext('Service') );
    $template->param( SRV_HOSTNAME_TEXT => gettext('Host') );
    $template->param( SRV_PORT_TEXT => gettext('Port') );
    $template->param( SRV_PRIORITY_TEXT => gettext('Priority') );
    $template->param( SRV_WEIGHT_TEXT => gettext('Weight') );

    $template->param( TEXT_SUBMIT => gettext("Submit") );

    # Treat TXT part
    $template->param( TEXT_LIST_TXT => gettext('List all TXT records') );
    $template->param( TEXT_ADD_TXT => gettext('Add a TXT record') );
    $template->param( TEXT_TYPETXT => gettext('All TXT records for your domain name') );
    $template->param( TXT_DATA_TEXT => gettext('Text') );
    $template->param( TXT_NAME_TEXT => gettext('Name for record') );

    if( scalar(keys %{$a_rr}) ) {
        my $thirdtemplate = new HTML::Template( filename => $templatedir.'/panel/dns/list_a_sub.tmpl', global_vars => 1, die_on_bad_params => 0);
        my @list_a = sort {$a->{name} cmp $b->{name}} values(%{$a_rr});
        $thirdtemplate->param( LIST_HELP => sprintf(gettext( '@ represents the origin (%s)' ), $domain_name) );
	    $thirdtemplate->param( DEL => gettext( 'Delete' ) );
        $thirdtemplate->param( DOMAIN => $domain_name );
        $thirdtemplate->param( MODIFY => gettext( 'Modify' ) );
        $thirdtemplate->param( A_RR => \@list_a);
    	$template->param( LIST_A => $thirdtemplate->output );
    } else {
    	$template->param( LIST_A => gettext('No A type found' ));
    }

    if( scalar(keys %{$aaaa}) ) {
        my $thirdtemplate = new HTML::Template( filename => $templatedir.'/panel/dns/list_aaaa_sub.tmpl', global_vars => 1, die_on_bad_params => 0);
        my @list_aaaa = sort {$a->{name} cmp $b->{name}} values(%{$aaaa});
	    $thirdtemplate->param( DEL => gettext( 'Delete' ) );
        $thirdtemplate->param( DOMAIN => $domain_name );
        $thirdtemplate->param( MODIFY => gettext( 'Modify' ) );
        $thirdtemplate->param( AAAA_RR => \@list_aaaa);
    	$template->param( LIST_AAAA => $thirdtemplate->output );
    } else {
    	$template->param( LIST_AAAA => gettext('No AAAA type found' ));
    }


	if( scalar(keys %{$mx} ) ) {
        $thirdtemplate = new HTML::Template( filename => $templatedir.'/panel/dns/list_mx_sub.tmpl', global_vars => 1, die_on_bad_params => 0 );
        my @list_mx = sort {$a->{name} cmp $b->{name}} sort {$a->{aux} <=> $b->{aux}} values(%{$mx});
        $thirdtemplate->param( DEL => gettext( 'Delete' ) );
        $thirdtemplate->param( DOMAIN => $domain_name );
        $thirdtemplate->param( MODIFY => gettext( 'Modify' ) );
        $thirdtemplate->param( TEXT_PRIORITY => gettext( 'Priority: ' ));
        $thirdtemplate->param( MX_RR => \@list_mx );
		$template->param( LIST_MX => $thirdtemplate->output );
    } else {
        $template->param( LIST_MX => gettext( 'No MX reccord for this domain' ));
    }

    if( scalar(keys %{$cnames} ) ) {
        $thirdtemplate = new HTML::Template( filename => $templatedir.'/panel/dns/list_cname_sub.tmpl', global_vars => 1, die_on_bad_params => 0 );
        $thirdtemplate->param( DEL => gettext( 'Delete' ) );
        $thirdtemplate->param( MODIFY => gettext( 'Modify' ) );
        $thirdtemplate->param( DOMAIN => $domain_name );
        my @list_cname = sort {$a->{name} cmp $b->{name}} values(%{$cnames});
        $thirdtemplate->param( CNAME_RR => \@list_cname );

   		$template->param( LIST_CNAME => $thirdtemplate->output );
    } else {
        $template->param( LIST_CNAME => gettext( 'No CNAME available on this domain' ) );
    }



    if( scalar(keys %{$ns}) ) {
        my @list_ns = sort {$a->{name} cmp $b->{name}} sort {$a->{data} cmp $b->{data}} values(%{$ns});
        $thirdtemplate = new HTML::Template( filename => $templatedir.'/panel/dns/list_ns_sub.tmpl', global_vars => 1, die_on_bad_params => 0 );
        $thirdtemplate->param( DEL => gettext( 'Delete' ) );
        $thirdtemplate->param( DOMAIN => $domain_name );
        $thirdtemplate->param( NS_RR => \@list_ns );
        $template->param( LIST_NS => $thirdtemplate->output );
    } else {
        $template->param( LIST_NS => gettext( "No NS available on this domain") );
    }

    if( scalar(keys %{$srv}) ) {
        my @list_srv = sort {$a->{name} cmp $b->{name}} values(%{$srv});
        $thirdtemplate = new HTML::Template( filename => $templatedir.'/panel/dns/list_srv_sub.tmpl', global_vars => 1, die_on_bad_params => 0 );
        $thirdtemplate->param( DEL => gettext( 'Delete' ) );
        $thirdtemplate->param( MODIFY => gettext( 'Modify' ) );
        $thirdtemplate->param( DOMAIN => $domain_name );
        $thirdtemplate->param( HOST_TXT => gettext( 'Host' ) );
        $thirdtemplate->param( PORT_TXT => gettext( 'Port' ) );
        $thirdtemplate->param( PRIORITY_TXT => gettext( 'Priority' ) );
        $thirdtemplate->param( WEIGHT_TXT => gettext( 'Weight' ) );
        $thirdtemplate->param( SRV_RR => \@list_srv );
        $template->param( LIST_SRV => $thirdtemplate->output );
    } else {
        $template->param( LIST_SRV => gettext( 'No SRV available on this domain') );
    }

    if( scalar(keys %{$txt}) ) {
        my @list_txt = sort {$a->{data} cmp $b->{data}} values(%{$txt});
        $thirdtemplate = new HTML::Template( filename => $templatedir.'/panel/dns/list_txt_sub.tmpl', global_vars => 1, die_on_bad_params => 0 );
        $thirdtemplate->param( DEL => gettext( 'Delete' ) );
        $thirdtemplate->param( MODIFY => gettext( 'Modify' ) );
        $thirdtemplate->param( DOMAIN => $domain_name );
        $thirdtemplate->param( HOST_TXT => gettext( 'Host' ) );
        $thirdtemplate->param( TXT_RR => \@list_txt );
        $template->param( LIST_TXT => $thirdtemplate->output );
    } else {
        $template->param( LIST_TXT => gettext( 'No TXT available on this domain') );
    }


	my $adminpart = Vhffs::Panel::Object::admin_part( $panel, $dns );
	$template->param( ADMIN_PART => $adminpart->output ) if( defined $adminpart );
}

$panel->build( $template );
$panel->display;
