#!/usr/bin/perl

# ---------------------------------------------------------------
# Prontus CMS
# http://www.prontus.cl
# by Altavoz.net
#
# licensed under LGPL license.
# http://www.prontus.cl/license.html
# ---------------------------------------------------------------

# -------------------------------COMENTARIO GLOBAL---------------
# ---------------------------------------------------------------
# SCRIPT.
# -----------
# prontus_corrige_friendly4.pl
# ---------------------------------------------------------------
# UBICACION.
# -----------
# ---------------------------------------------------------------
# PROPOSITO.
# -----------
# Ejecuta la transcodificación para todos los videos de un prontus
# de la misma forma que se hace desde un FID
# ---------------------------------------------------------------
use strict;
use utf8;

BEGIN {
    use FindBin qw($Bin);
    unshift(@INC,$Bin); # Para dejar disponibles las librerias
    my $pathLibsProntus = $Bin;
    $pathLibsProntus =~ s/\/[^\/]+\/?$//;
    unshift(@INC,$pathLibsProntus); # Para dejar disponibles las librerias de prontus
}

use lib_prontus;
use Artic;
# Captura STDERR
use lib_stdlog;
&lib_stdlog::set_stdlog($0, 51200);

use DBI;

use prontus_varglb; &prontus_varglb::init();
use glib_hrfec_03;
use glib_html_03;
use glib_fildir_03;
use lib_mam;

# ---------------------------------------------------------------
# MAIN.
# ---------------------------------------------------------------
my $separator_orig = '   ';
my $separator = '';
my $counter = 0;

my @marcas = ('_fid','_txt_titular','_custom_slug','_slug');
my $PRONTUS_ID = '';
my $BD;
my $input = $Bin;

main:{
    &lib_prontus::setUtf8();
    $PRONTUS_ID = $ARGV[0];

    if (scalar @ARGV < 1) {
        print "Parametros insuficientes Terminando\n";
        exit;
    }

    my $msg_load = &lib_prontus::load_config_by_id($PRONTUS_ID);
    if ($msg_load ne '') {
        print STDERR "Error: $msg_load\n";
        print "Error: $msg_load\n";
        exit;
    }

    if ($prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'FRIENDLY_URLS_VERSION'} eq 'N') {
        print "Prontus [$PRONTUS_ID] no tiene friendly url activada\n";
        exit;
    } elsif ($prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'FRIENDLY_URLS_VERSION'} ne '4') {
        print "Prontus [$PRONTUS_ID] no tiene friendly url v4 activada\n";
        exit;
    }

    my $msg_err_bd;
    ($BD, $msg_err_bd) = &lib_prontus::conectar_prontus_bd();

    if (!ref($BD)) {
        print STDERR "Error conectar BD: $msg_err_bd\n";
        print "Error conectar BD: $msg_err_bd\n";
        &glib_html_03::print_json_result(0, "Error conectar BD: $msg_err_bd");
        exit;
    };

    $input = $prontus_varglb::DIR_SERVER ."/$PRONTUS_ID/site/artic/";
    print "[".&glib_hrfec_03::fecha_human()." ". &glib_hrfec_03::hora_human()."] Inicio Proceso\n";
    print "ID;TS;FID;TITULAR;SLUG_ORIGINAL;SLUG_NUEVO;URL_DIRECTA;URL_FRIENDLY\n";
    &procesa_dir($input);
    print 'Se encontraron ' . $counter .  ' archivos ' . "\n";
    print "[".&glib_hrfec_03::fecha_human()." ". &glib_hrfec_03::hora_human()."] Fin Proceso\n";
};

#-----------------------------------------------------------------------#
sub procesa_dir {
    my($input) = $_[0];

    unless(-d $input) {
        die "El directorio $input no existe.";
    };
    $input = $input . '/' unless ($input =~ /\/$/);

    my @entries = &glib_fildir_03::lee_dir($input);
    foreach my $k (@entries) {
        next if($k eq '.' || $k eq '..');
        if(-f $input . $k) {
            &procesa_file($k, $input);

        } elsif(-d $input . $k) {
            $separator = $separator . $separator_orig;
            &procesa_dir($input . $k);
        }
    }
    $separator =~ s/$separator_orig$//;
}
#-----------------------------------------------------------------------#
sub procesa_file {
    my($filename, $path) = ($_[0], $_[1]);
    my $filepath = $path . $filename;
    my $ts;
    if ($filename !~ /^(\d+?)\.xml/isg) {
        return;
    }
    $ts = $1;

    if (-f $filepath) {
        my $xml_data = &glib_fildir_03::read_file($filepath);
        my $fid;

        if ($xml_data =~ /<_fid>(.*?)<\/_fid>/is) {
            $fid = $1;
            $fid =~ s/[\n\r]//g;
        } else {
            print STDERR "Artículo [$filepath] [$ts] no tiene fid asignado\n";
            next;
        }


        if (exists $prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'FRIENDLY_EXCLUDE_FID'}{$fid}) {
            next;
        }

        my $artic_obj;
        unless($artic_obj = Artic->new(
                    'document_root'      => $prontus_varglb::DIR_SERVER,
                    'prontus_id'         => $prontus_varglb::PRONTUS_ID,
                    'public_server_name' => $prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'PUBLIC_SERVER_NAME'},
                    'cpan_server_name'   => $prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'CPAN_SERVER_NAME'},
                    'ts'                 => $ts,
                    'no_check_dirs'      => 1)) {
            print "[$ts] Error inicializando objeto articulo: $Artic::ERR\n";
            return '';
        };

        # cargamos los campos del xml
        my %campos = $artic_obj->get_xml_content();
        my $slug_original = '';

        # revisamos si se usa el slug custom para verificar colision
        if ($campos{'_custom_slug'} eq 'SI') {
            $slug_original = &lib_prontus::ajusta_titular_friendly($campos{'_slug'});
        } else {
            $slug_original = &lib_prontus::ajusta_titular_friendly($campos{'_txt_titular'});
        }

        my $nuevo_slug = $slug_original;
        my $changed = 0;
        for (my $i = 1; $i < 50; $i++) {
            if ($artic_obj->verifica_colision_url_titular($BD, $nuevo_slug)) {
                my $new_string = '-' . $i;
                if (length($slug_original) > ($prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'FRIENDLY_URLS_LARGO_TITULAR'} - length($new_string))) {
                    $nuevo_slug = substr($slug_original, 0, $prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'FRIENDLY_URLS_LARGO_TITULAR'} - length($new_string)). $new_string;
                } else {
                    $nuevo_slug = $slug_original . '-' . $i;
                }
                $nuevo_slug =~ s/-+/-/g;
                $changed = 1;
            } else {
                last;
            }
        }

        if ($changed) {
            if ($xml_data =~ /<_slug>.*?<\/_slug>/s) {
                $xml_data =~ s/<_slug>.*?<\/_slug>/<_slug>$nuevo_slug<\/_slug>/is;
            } else {
                $xml_data =~ s/<\/_txt_titular>/<\/_txt_titular>\n<_slug>$nuevo_slug<\/_slug>/is;
            }

            if ($xml_data =~ /<_custom_slug>.*?<\/_custom_slug>/s) {
                $xml_data =~ s/<_custom_slug>.*?<\/_custom_slug>/<_custom_slug>SI<\/_custom_slug>/is;
            } else {
                $xml_data =~ s/<\/_txt_titular>/<\/_txt_titular>\n<_custom_slug>SI<\/_custom_slug>/is;
            }

            # se actualiza el xml de articulo
            &glib_fildir_03::write_file($artic_obj->{'fullpath_xml'}, $xml_data);
            # recargamos los campos
            $artic_obj->{'xml_content'} = {};
            my %campos = $artic_obj->get_xml_content();

            # generamos el link v4
            $artic_obj->genera_friendly_v4($BD);

            # Generar vista (a partir del xml)
            $artic_obj->generar_vista_art('') || &registra_artic_error("\t\t\t\tError: $Artic::ERR");

            foreach my $mv (keys %{$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'MULTIVISTAS'}}) {
                # Generar vista (a partir del xml)
                $artic_obj->generar_vista_art($mv) || &registra_artic_error("\t\t\t\tError: $Artic::ERR");
            }
            my $relpath_artic = '/'.$PRONTUS_ID.'/site/artic/' . substr($ts, 0, 8) . '/pags/'. $ts . '.html';

            my %artic_data = ();
            $artic_data{'fid'} = $campos{'_fid'};
            $artic_data{'custom_slug'} = $campos{'_custom_slug'};
            $artic_data{'slug'} = $campos{'_slug'};
            $artic_data{'nom_seccion'} = $campos{'_nom_seccion1'};
            $artic_data{'nom_tema'} = $campos{'_nom_tema1'};
            $artic_data{'nom_subtema'} = $campos{'_nom_subtema1'};

            my $friendlyUrl = &lib_prontus::parse_filef('%%_FILEURL%%', $campos{'_txt_titular'}, $ts, $PRONTUS_ID, $relpath_artic, \%artic_data);
            $campos{'_txt_titular'} =~ s/[\n\r\t]+/ /g;
            $campos{'_txt_titular'} =~ s/"//g;

            print "$campos{'_art_autoinc'};$ts;$campos{'_fid'};\"$campos{'_txt_titular'}\";\"$slug_original\";\"$campos{'_slug'}\";\"$relpath_artic\";\"$friendlyUrl\"\n";

            $counter++;
        }
    }
}
