#!/usr/bin/perl

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

# -------------------------------COMENTARIO GLOBAL---------------
# ---------------------------------------------------------------
# PROPOSITO.
# -----------
# Ejecuta tareas de ajustes necesarias despúes de actualizar prontus
# requeridas por nuevas funciones implementadas
# ---------------------------------------------------------------
# LLAMADAS A ARCHIVOS EXTERNOS.
# ------------------------------
#
# ---------------------------------------------------------------
# INVOCACIONES ACEPTADAS.
# ------------------------
# Por linea de comando
# ---------------------------------------------------------------

# ---------------------------------------------------------------
# DIRECTIVAS DE COMPILACION.
# ---------------------------
use utf8;
use strict;

BEGIN {
    use FindBin qw($Bin);
    my $pathLibsProntus = $Bin;
    unshift(@INC,$pathLibsProntus);
    $pathLibsProntus = "$Bin/multitag";
    unshift(@INC,$pathLibsProntus);
}

use sigtrap 'handler' => \&signal_catch, 'INT';
use sigtrap 'handler' => \&signal_catch, 'TERM';
use sigtrap 'handler' => \&signal_catch, 'KILL';

##libs##
# Captura STDERR
use lib_stdlog;
lib_stdlog::set_stdlog($0, 51200);

use File::Copy qw(move);
use Encode qw(decode);
use Data::Dumper;

use lib_maxrunning;
use glib_fildir_03;
use prontus_varglb; &prontus_varglb::init();
use glib_html_03;
use lib_prontus;
use lib_tags;
use lib_tax;
use lib_multitag;
use lib_setbd;
##/libs##

my $ERROR = '';

main: {
    &lib_prontus::setUtf8();
    if (&lib_maxrunning::maxExcedido(1)) {
        exit;
    }
    print STDERR "[" . &glib_hrfec_03::get_dtime_pack4() . "] Iniciando tareas de actualización de Prontus\n";
    my $status_file = "$prontus_varglb::DIR_SERVER/prontus/cpan/data/prontus_updated.json";
    &glib_fildir_03::check_dir("$prontus_varglb::DIR_SERVER/prontus/cpan/data/");
    &glib_fildir_03::write_file($status_file, '{"status": 1, "progress":0, "msg":"procesando"}');

    my $worker = "$prontus_varglb::DIR_SERVER/prontusSW.min.js";
    if (!-f $worker && !-l $worker) {
        my $cmd = "ln -sr $prontus_varglb::DIR_SERVER/prontus/front/prontusPush/prontusSW.min.js $worker 2>&1";
        my $res = `$cmd`;
        print STDERR $res, "\n";
    }

    # path de cgis-cpn para ejecutar scripts
    my $path_cgicpn = "$prontus_varglb::DIR_SERVER/$prontus_varglb::DIR_CGI_CPAN";

    # definicion de columnas de bd que hay que cambiar de tipo char a numerico respecto a versiones anteriores de prontus
    my @columnas_bd = (
        {'table' => 'TAGSART', 'column' => 'TAGSART_IDART', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'ASSET', 'column' => 'ASSET_ART_ID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'ART', 'column' => 'ART_ID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'ART', 'column' => 'ART_AUTOR', 'coldef' => "varchar(64) not null default ''"},
        {'table' => 'ART', 'column' => 'ART_HORAP', 'coldef' => 'int(4) unsigned zerofill not null default 0'},
        {'table' => 'ART', 'column' => 'ART_HORAE', 'coldef' => 'int(4) unsigned zerofill not null default 0'},
        {'table' => 'ART', 'column' => 'ART_DIRFECHA', 'coldef' => 'int(8) unsigned zerofill not null default 0'},
        {'table' => 'ART', 'column' => 'ART_FECHAP', 'coldef' => 'int(8) unsigned zerofill not null default 0'},
        {'table' => 'ART', 'column' => 'ART_FECHAE', 'coldef' => 'int(8) unsigned zerofill not null default 99999999'},
        {'table' => 'ART', 'column' => 'ART_FECHAEHORAE', 'coldef' => 'bigint(12) unsigned zerofill not null default 999999990000'},
        {'table' => 'ART', 'column' => 'ART_FECHAPHORAP', 'coldef' => 'bigint(12) unsigned zerofill not null default 0'},
        {'table' => 'ART_PUBLICAR', 'column' => 'ART_ID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'ART_PUBLICAR', 'column' => 'ART_FECHAPHORAP', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'ART_DESPUBLICAR', 'column' => 'ART_ID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'ART_DESPUBLICAR', 'column' => 'ART_FECHAEHORAE', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'URL', 'column' => 'URL_ART_ID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'URLF5', 'column' => 'URLF5_SUBTYPEID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'MULTITAG_ART_S', 'column' => 'MULTITAG_ART_S_ART_ID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'MULTITAG_ART_T', 'column' => 'MULTITAG_ART_T_ART_ID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'MULTITAG_ART_ST', 'column' => 'MULTITAG_ART_ST_ART_ID', 'coldef' => 'bigint unsigned not null default 0'},
        {'table' => 'USERS', 'column' => 'USERS_NOM', 'coldef' => "varchar(64) not null default ''"});

    my @index_tables = (
        {'table' => 'URLF5', 'column' => 'URLF5_SUBTYPEID'},
        {'table' => 'ASSET', 'column' => 'ASSET_FILE'},
        {'table' => 'ASSET', 'column' => 'ASSET_ART_ID'},
        {'table' => 'ASSET', 'column' => 'ASSET_PIX'},
        {'table' => 'ASSET', 'column' => 'ASSET_ORIGINAL'},
        {'table' => 'SECC', 'column' => 'SECC_MOSTRAR'},
        {'table' => 'SECC', 'column' => 'SECC_ORDEN'},
        {'table' => 'TEMAS', 'column' => 'TEMAS_MOSTRAR'},
        {'table' => 'TEMAS', 'column' => 'TEMAS_ORDEN'},
        {'table' => 'SUBTEMAS', 'column' => 'SUBTEMAS_MOSTRAR'},
        {'table' => 'SUBTEMAS', 'column' => 'SUBTEMAS_ORDEN'},
        {'table' => 'TAGS', 'column' => 'TAGS_MOSTRAR'},
        {'table' => 'ART', 'column' => 'ART_IDTEMAS1'},
        {'table' => 'ART', 'column' => 'ART_IDSUBTEMAS1'},
        {'table' => 'ART', 'column' => 'ART_IDTEMAS2'},
        {'table' => 'ART', 'column' => 'ART_IDSUBTEMAS2'},
        {'table' => 'ART', 'column' => 'ART_IDTEMAS3'},
        {'table' => 'ART', 'column' => 'ART_IDSUBTEMAS3'},
        {'table' => 'ART', 'column' => 'ART_AUTOR'},
        {'table' => 'ART', 'column' => 'ART_FECHAE'},
        {'table' => 'ART', 'column' => 'ART_TITU'},
        {'table' => 'ART', 'column' => 'ART_BAJA'},
        {'table' => 'ART', 'column' => 'ART_IDUSR'},
        {'table' => 'ART', 'column' => 'ART_SOLOPORTADAS'},
        {'table' => 'ART', 'column' => 'ART_FECHA_INICIO'},
        {'table' => 'ART', 'column' => 'ART_FECHA_FIN'},
        {'table' => 'ART', 'column' => 'ART_MODTIME'},
        {'table' => 'ART', 'column' => 'ART_S3_SIZE'},
        {'table' => 'ART', 'column' => 'ART_S3'},
        {'table' => 'ART', 'column' => 'ART_INDEXAR'},
        {'table' => 'URLF5', 'column' => 'URLF5_TYPE'},
        {'table' => 'URLF5', 'column' => 'URLF5_FILE'},
        {'table' => 'MULTITAG_S', 'column' => 'MULTITAG_S_ESTADO'},
        {'table' => 'MULTITAG_T', 'column' => 'MULTITAG_T_ESTADO'},
        {'table' => 'MULTITAG_ST', 'column' => 'MULTITAG_ST_ESTADO'},
        {'table' => 'USERS', 'column' => 'USERS_DELETED'},
        {'table' => 'USERS', 'column' => 'USERS_EMAIL'},
        {'table' => 'OIDC_USERS', 'column' => 'OIDC_IDUSERS'},
        {'table' => 'OLD_PSW', 'column' => 'USERS_ID'},
        {'table' => 'PORT_USERS', 'column' => 'PORT_USER_ID'},
        {'table' => 'ART_USERS', 'column' => 'ART_USER_ID'},
        {'table' => 'PRONTUS_USERS', 'column' => 'PRONTUS_USER_ID'},
        {'table' => 'PRONTUS_USERS', 'column' => 'PRONTUS_ID'},
    );

    my @prontus_dirs = &lib_prontus::get_prontus_dirs();
    my $prontus_count = scalar @prontus_dirs;
    my $counter = 0;
    my $prontus_percent = 1/$prontus_count;

    # borramos archivos que ya no se usan y fueron removidos de la release
    my @delete_files = (
        '/cgi-bin/coment/coment_enviar.cgi',
        '/cgi-bin/coment/lib_custom_val_sample.pm',
        '/cgi-bin/coment/lib_ipcheck.pm',
        '/cgi-bin/coment/lib_phpsession.pm',
        '/cgi-bin/coment/lib_val.pm',
        '/cgi-bin/dir_cgi.pm',
        '/cgi-cpn/coment/coment_admin.cgi',
        '/cgi-cpn/coment/coment_borrar.cgi',
        '/cgi-cpn/coment/coment_cambia_st.cgi',
        '/cgi-cpn/coment/coment_regenera.cgi',
        '/cgi-cpn/coment/coment_varglb.pm',
        '/cgi-cpn/coment/lib_coment.pm',
        '/cgi-cpn/mam/lib_fechas.pm',
        '/cgi-cpn/mam/lib_mam.pm',
        '/cgi-cpn/dir_cgi.pm',
        '/cgi-cpn/prontus_admin_conf_coment.cgi',
        '/cgi-cpn/prontus_art_facebook_post.cgi',
        '/cgi-cpn/prontus_art_youtube_post.cgi',
        '/cgi-cpn/prontus_batch_ext-media_asoc.pl',
        '/cgi-cpn/prontus_regen_check_proccess.cgi',
        '/cgi-cpn/prontus_tags_import_archivo.cgi',
        '/cgi-cpn/prontus_tax_import_archivo.cgi',
        '/prontus/cpan/dir_cgi.js',
        '/prontus/cpan/editor_imag/js-local/cropper/cropper.css',
        '/prontus/cpan/editor_imag/js-local/cropper/cropper.js',
        '/prontus/cpan/editor_imag/js-local/cropper/cropper.min.css',
        '/prontus/cpan/editor_imag/js-local/cropper/cropper.min.js',
        '/prontus/cpan/facebook_post/libs/Utiles.class.php',
        '/prontus/cpan/facebook_post/sdk/config.php',
        '/prontus/cpan/facebook_post/sdk/php-graph-sdk-5.4/Exceptions/FacebookResumableUploadException.php',
        '/prontus/cpan/flash/player_video/playerVideo.swf',
        '/prontus/cpan/imag/boto/mover2.png',
        '/prontus/cpan/imag/boto/mover2_of.png',
        '/prontus/cpan/imag/boto/mover2_on.png',
        '/prontus/cpan/js-local/prontus.js',
        '/prontus/cpan/js-local/Coment.class.js',
        '/prontus/cpan/js-local/Cookies.class.js',
        '/prontus/cpan/js-local/Editor.class.js',
        '/prontus/cpan/js-local/Editor_funciones.js',
        '/prontus/cpan/js-local/EventosTags.class.js',
        '/prontus/cpan/js-local/Extras.class.js',
        '/prontus/cpan/js-local/TaxEvents.class.js',
        '/prontus/cpan/js-local/Utf8.class.js',
        '/prontus/cpan/js-local/Acciones.class.js',
        '/prontus/cpan/js-local/clipboard/clipboard.js',
        '/prontus/cpan/plantillas/coment/coment_admin.html',
        '/prontus/cpan/plantillas/coment/coment_errmsg.html',
        '/prontus/cpan/plantillas/coment/gadgets/ver_artic.html',
        '/prontus/cpan/plantillas/core/new_xml.xml',
        '/prontus/cpan/plantillas/core/prontus_admin_conf_coment.html',
        '/prontus/cpan/plantillas/core/prontus_seccion_admin.html',
        '/prontus/cpan/plantillas/core/prontus_seccion_nueva.html',
        '/prontus/cpan/plantillas/core/prontus_subtema_admin.html',
        '/prontus/cpan/plantillas/core/prontus_tags_import.html',
        '/prontus/cpan/plantillas/core/prontus_tax_import.html',
        '/prontus/cpan/plantillas/core/prontus_tema_admin.html',
        '/prontus/cpan/plantillas/core/rowartics.xml',
        '/prontus/cpan/plantillas/fid/macros_reservadas/_general_comentarios.html',
        '/prontus/cpan/plantillas/prontus_edit/prontus_edit_arbol.html'
        );

    foreach my $files (@delete_files) {
        unlink "$prontus_varglb::DIR_SERVER$files";
    }

    print STDERR "Prontus count [$prontus_count] ". join(';', @prontus_dirs). "\n";
    # Iterar por cada prontus
    foreach my $prontus_dir (@prontus_dirs) {
        print STDERR "Procesando prontus_dir[$prontus_dir]\n";
        my $ready = 100*$counter/$prontus_count;
        $counter++;

        # se reinician los valores de prontus_varglb
        &prontus_varglb::init();
        # Carga variables de configuracion.
        my $msg_load = &lib_prontus::load_config_by_id($prontus_dir);
        if ($msg_load ne '') {
            print STDERR "Error al cargar configuracion: $msg_load\n";
            next;
        }

        # crea directorios necesarios para el funcionamiento de Prontus, por si se agregaron nuevos directorios
        &lib_prontus::check_dirs();
        &update_progress($status_file, int($ready+$prontus_percent*2));

        # mueve respaldos de artículos para que sean usables por el sistema de versiones anteriores
        my $dir_bkp = $prontus_varglb::DIR_SERVER . $prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_SITE'} . $prontus_varglb::DIR_BKP;
        if (opendir(DIR, $dir_bkp)) {
            my @files = readdir(DIR);
            closedir DIR;
            foreach my $file (@files) {
                next if ($file eq '.' or $file eq '..');
                if ($file =~ /^(\d{14})\.xml.\d+$/) {
                    my $ts = $1;
                    my $modtime = (stat("$dir_bkp/$file"))[9];
                    my $fechac = substr($ts, 0, 8);
                    glib_fildir_03::check_dir("$dir_bkp/$fechac");
                    move("$dir_bkp/$file", "$dir_bkp/$fechac/$ts.xml.$modtime");

                }
            }
        }
        &update_progress($status_file, int($ready+$prontus_percent*4));

        # empiezan modificaciones a BD
        my $msg_err_bd = '';
        ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $msg_err_bd) = &lib_prontus::conectar_prontus_bd();
        if (! ref($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID})) {
            print STDERR "ERROR al conectar a BD: $msg_err_bd\n";
            print STDERR "No se procesará este Prontus\n";
            next;
        }

        # crear tablas de usuarios
        my ($msg_ret, $hay_err) = &lib_setbd::crear_tabla_usuarios($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        if (!$hay_err || $msg_ret =~ /ya existe/) {
            print STDERR "[$prontus_varglb::PRONTUS_ID] tabla USERS existe \n";
            # Valida si existe la columna USERS_2FA, si no la crea
            my $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "USERS", "USERS_2FA", "INT UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna USERS.USERS_2FA [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }
            # Valida si existe la columna USERS_DELETED, si no la crea
            $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "USERS", "USERS_DELETED", "INT(1) UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna USERS.USERS_DELETED [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }
            # Valida si existe la columna USERS_OIDC, si no la crea
            $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "USERS", "USERS_OIDC", "INT(1) UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna USERS.USERS_OIDC [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }

            my $sql = 'select count(*) from USERS';
            my $count_users = 0;
            my $salida = glib_dbi_03::ejecutar_sql_bind($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \($count_users));
            $salida->fetch;
            $salida->finish;

            # tabla vacia hay que cargar los datos
            if ($count_users < 1) {
                my %profiles = ('A' => 1, 'E' => 2, 'P' => 3 );
                if (open(my $DATA, '<', "$prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_DBM'}/users/users.txt")) {
                    binmode $DATA;
                    while (<$DATA>) {
                        $_ =~ s/\n$//;
                        my ($users_id, $users_nom, $users_usr, $users_psw, $users_perfil, $users_email, $users_exp_days, $users_fec_exp) = split(/\|/, $_);
                        $users_nom = decode('iso-8859-1', $users_nom, Encode::FB_DEFAULT);
                        if (length($users_nom) > 50) {
                            $users_nom = substr($users_nom, 0, 50);
                        }
                        if (length($users_usr) > 32) {
                            $users_usr = substr($users_usr, 0, 32);
                        }
                        if (length($users_psw) > 255) {
                            $users_psw = substr($users_psw, 0, 255);
                        }
                        if (length($users_email) > 255) {
                            $users_email = substr($users_email, 0, 255);
                        }

                        if ($users_id ne '' && $users_nom ne '' && $users_usr  ne '' && $users_psw ne '') {
                            $users_exp_days += 0;
                            $users_fec_exp += 0;
                            $sql = "INSERT INTO USERS (USERS_ID, USERS_NOM, USERS_USR, USERS_PSW, USERS_PROFILE_ID, USERS_EMAIL, USERS_EXP_DAYS, USERS_FEC_EXP, USERS_RENEW_PSW, USERS_2FA, USERS_OIDC, USERS_DELETED) VALUES(?, ?, ?, ?, ?, ?, ?, ?, 1, 0, 0, 0)";
                            my $perfil = 3; # perfil por defecto
                            if (defined($profiles{$users_perfil})) {
                                $perfil = $profiles{$users_perfil};
                            }
                            my @params = ($users_id, $users_nom, $users_usr, $users_psw, $perfil, $users_email, $users_exp_days, $users_fec_exp);
                            my $salida = &glib_dbi_03::ejecutar_sql_param($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \@params);

                            if ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr) {
                                print STDERR "Error actualizando la tabla USERS: sql[$sql][".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]";
                            }
                        }
                    }
                    close $DATA;
                } else {
                    print STDERR "Error al abrir: $prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_DBM'}/users/users.txt\n";
                }
            }
        } else {
            $ERROR = "($msg_ret, $hay_err)";
            exit;
        }
        &update_progress($status_file, int($ready+$prontus_percent*8));

        # agregamos nueva columna de permisos
        my $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "PROFILES", "PROFILES_PERMISSIONS", "TEXT");
        if (!$ret) {
            print STDERR "Error creando columna PROFILES.PROFILES_PERMISSIONS [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }

        # agregamos nuevas columnas de nombres vistas
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "MULTITAG_S", "MULTITAG_S_NOM4VISTAS", "text NOT NULL default ''");
        if (!$ret) {
            print STDERR "Error creando columna MULTITAG_S.MULTITAG_S_NOM4VISTAS [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "MULTITAG_T", "MULTITAG_T_NOM4VISTAS", "text NOT NULL default ''");
        if (!$ret) {
            print STDERR "Error creando columna MULTITAG_T.MULTITAG_T_NOM4VISTAS [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "MULTITAG_ST", "MULTITAG_ST_NOM4VISTAS", "text NOT NULL default ''");
        if (!$ret) {
            print STDERR "Error creando columna MULTITAG_ST.MULTITAG_ST_NOM4VISTAS [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }

        # actualizamos los perfiles si es necesario
        my $sql_update_perfiles = "update PROFILES set PROFILES_PERMISSIONS = 'cms_publish,art_publish,art_list,art_alta,art_index,art_edit_others,art_view_others,art_view_all,form_view,cms_publish,ports,edics,pltport,ports_vobo,ports_art_vobo,cms_publish,category,taxs,cms_publish,category,tags,cms_publish,category,multitag,multimedia' where PROFILES_ID=2 and (PROFILES_PERMISSIONS='' or PROFILES_PERMISSIONS is NULL)";
        my $salida_perfiles = glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql_update_perfiles);

        $sql_update_perfiles = "update PROFILES set PROFILES_PERMISSIONS = 'cms_publish,art_publish,art_list,form_view,cms_publish,ports,multimedia' where PROFILES_ID=3 and (PROFILES_PERMISSIONS='' or PROFILES_PERMISSIONS is NULL)";
        $salida_perfiles = glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql_update_perfiles);

        &update_progress($status_file, int($ready+$prontus_percent*10));

        # Agregamos columna TAGS_PORT si no existe
        my $tags_ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "TAGS", "TAGS_PORT", "VARCHAR(255) NOT NULL DEFAULT ''");
        if (!$tags_ret) {
            print STDERR "Error creando columna TAGS.TAGS_PORT [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }
        &update_progress($status_file, int($ready+$prontus_percent*12));

        ($msg_ret, $hay_err) = &lib_setbd::crear_tabla_oidc($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        if ($hay_err && $msg_ret !~ /ya existe/) {
            $ERROR = "($msg_ret, $hay_err)";
            exit;
        }
        &update_progress($status_file, int($ready+$prontus_percent*16));

        ($msg_ret, $hay_err) = &lib_setbd::crear_tabla_old_psw($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        if ($hay_err && $msg_ret !~ /ya existe/) {
            $ERROR = "($msg_ret, $hay_err)";
            exit;
        }
        &update_progress($status_file, int($ready+$prontus_percent*20));

        ($msg_ret, $hay_err) = &lib_setbd::crear_tabla_urlf5($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $prontus_varglb::URL_MAX_LENGTH);
        if ($hay_err && $msg_ret !~ /ya existe/) {
            $ERROR = "($msg_ret, $hay_err)";
            exit;
        } elsif ($msg_ret =~ /ya existe/) {
            my $sql = "ALTER TABLE URLF5 CONVERT TO CHARACTER SET ascii COLLATE ascii_general_ci";
            my $salida = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql);
            $salida->finish;

            $sql = "ALTER TABLE URLF5 MODIFY URLF5_URL VARCHAR($prontus_varglb::URL_MAX_LENGTH)";
            $salida = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql);
            $salida->finish;
        }
        &update_progress($status_file, int($ready+$prontus_percent*24));

        my $regen_dam = 0;
        # verificamos si existe la columna ASSET_PLACEMENT
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ASSET", "ASSET_PLACEMENT");
        if (!$ret) {
            # columna no exite, se creara al regenerar el dam
            $regen_dam = 1;
        }

        &update_progress($status_file, int($ready+$prontus_percent*28));

        # verificamos si existe la columna ASSET_PIX
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ASSET", "ASSET_PIX");
        if (!$ret) {
            # columna no exite, se creara al regenerar el dam
            $regen_dam = 1;
        }

        &update_progress($status_file, int($ready+$prontus_percent*32));

        if ($regen_dam) {
            my $cmd = "$path_cgicpn/dam/prontus_dam_regen_real.cgi $prontus_varglb::PRONTUS_ID >/dev/null 2>&1 &";
            print STDERR "[" . &glib_hrfec_03::get_dtime_pack4() . "]$cmd\n";
            system $cmd;
        } else {
            # si no se regenera el dam verificamos que exista la columna
            # Valida si existe la columna ASSET_ORIGINAL, si no la crea
            $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ASSET", "ASSET_ORIGINAL", "TINYINT UNSIGNED NOT NULL DEFAULT 1");
            if (!$ret) {
                print STDERR "Error creando columna ASSET.ASSET_ORIGINAL [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            } elsif ($ret == 1) {
                # se agrego columna nueva, cambiar todos a original?
            }
        }
        &update_progress($status_file, int($ready+$prontus_percent*36));

        # agregamos un index para joins de la tabla URL con ART. Esto fallará si ya existe, pero no nos importa.
        my $exist = glib_dbi_03::check_index_table($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, 'URL', 'URL_ART_ID', 'TS');
        if (!$exist) {
            my $sql_url = "ALTER TABLE URL ADD UNIQUE INDEX TS (URL_ART_ID)";
            my $salida_url = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql_url);
            $salida_url->finish;
        }

        ($msg_ret, $hay_err) = &lib_setbd::crear_tabla_perfiles($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        if ($hay_err && $msg_ret !~ /ya existe/) {
            $ERROR = "($msg_ret, $hay_err)";
            exit;
        }
        &update_progress($status_file, int($ready+$prontus_percent*40));

        ($msg_ret, $hay_err) = &lib_setbd::crear_tabla_port_users($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        if (!$hay_err || $msg_ret =~ /ya existe/) {
            my $sql = 'select count(*) from PORT_USERS';
            my $count_portusers;
            my $salida = &glib_dbi_03::ejecutar_sql_bind($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \($count_portusers));
            $salida->fetch;
            $salida->finish;

            # tabla vacia hay que cargar los datos
            if ($count_portusers < 1 && -s "$prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_DBM'}/users/portusers.txt") {
                # PORTUSERS
                my ($port, $usr);
                if (open(my $DATA, '<', "$prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_DBM'}/users/portusers.txt")) {
                    while (<$DATA>) {
                        $_ =~ s/\n$//;
                        ($port, $usr) = split(/\|/, $_);
                        if ($port ne '' && $usr ne '') {
                            $usr += 0;
                            $sql = "insert into PORT_USERS values(?, ?, ?)";

                            my @params = ($usr, $port, $prontus_varglb::PRONTUS_ID);
                            my $salida = &glib_dbi_03::ejecutar_sql_param($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \@params);

                            if ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr) {
                                print STDERR "Error actualizando la tabla PORT_USERS: sql[$sql][".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
                            }
                        }
                    }
                    close $DATA;
                } else {
                    print STDERR "Error al abrir: $prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_DBM'}/users/portusers.txt\n";
                }
            }
        } else {
            $ERROR = "($msg_ret, $hay_err)";
            exit;
        }
        &update_progress($status_file, int($ready+$prontus_percent*44));

        ($msg_ret, $hay_err) = &lib_setbd::crear_tabla_art_users($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        if (!$hay_err || $msg_ret =~ /ya existe/) {
            my $sql = 'select count(*) from ART_USERS';
            my $count_artusers;
            my $salida = &glib_dbi_03::ejecutar_sql_bind($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \($count_artusers));
            $salida->fetch;
            $salida->finish;

            # tabla vacia hay que cargar los datos
            if ($count_artusers < 1 && -s "$prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_DBM'}/users/artusers.txt") {
                # ARTUSERS
                # carga los datos del prontus local
                if (open(my $DATA, '<', "$prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_DBM'}/users/artusers.txt")) {
                    while (<$DATA>) {
                        $_ =~ s/\n$//;
                        my ($art, $usr) = split(/\|/, $_);
                        if ($art ne '' && $usr ne '') {
                            $usr += 0;
                            $sql = "insert into ART_USERS values(?, ?, ?)";

                            my @params = ($usr, $art, $prontus_varglb::PRONTUS_ID);
                            my $salida = &glib_dbi_03::ejecutar_sql_param($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \@params);

                            if ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr) {
                                print STDERR "Error actualizando la tabla ART_USERS: sql[$sql][".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
                            }
                        }
                    }
                    close $DATA;
                } else {
                    print STDERR "Error al abrir: $prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_DBM'}/users/artusers.txt\n";
                }
            }
        } else {
            $ERROR = "($msg_ret, $hay_err)";
            exit;
        }
        &update_progress($status_file, int($ready+$prontus_percent*46));

        ($msg_ret, $hay_err) = &lib_setbd::crear_tabla_prontus_users($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        if (!$hay_err || $msg_ret =~ /ya existe/) {
            my $sql = 'select count(*) from PRONTUS_USERS';
            my $count_prontususers;
            my $salida = glib_dbi_03::ejecutar_sql_bind($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \($count_prontususers));
            $salida->fetch;
            $salida->finish;
            # tabla vacia, asigna permiso de acceso a prontus a los usuarios
            if ($count_prontususers < 1) {
                # si hay sso le asigna permisos de acceso a todos los pronts que maneja este prontus
                my @prontus_list;
                if ($prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'PRONTUS_SSO'} eq 'SI'
                    && $prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'PRONTUS_SSO_MANAGER_ID'} eq $prontus_varglb::PRONTUS_ID) {
                    @prontus_list = lib_prontus::get_prontus_sso_dirs();
                } else {
                    @prontus_list = ($prontus_varglb::PRONTUS_ID);
                }
                $sql = "SELECT USERS_ID FROM USERS WHERE USERS_ID > 1";
                my $user_id;
                $salida = glib_dbi_03::ejecutar_sql_bind($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \($user_id));
                while ($salida->fetch) {
                    foreach my $prontus (@prontus_list) {
                        $sql = "INSERT INTO PRONTUS_USERS values(?, ?)";
                        my @insert_data = ($user_id, $prontus);
                        glib_dbi_03::ejecutar_sql_param($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \@insert_data);
                        if ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr) {
                            print STDERR "Error actualizando la tabla PRONTUS_USERS: sql[$sql][".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
                        }
                    }
                }
                $salida->finish;
            }
        } else {
            $ERROR = "($msg_ret, $hay_err)";
            exit;
        }
        &update_progress($status_file, int($ready+$prontus_percent*48));

        # columnas nuevas para ART
        # Valida si existe la columna ART_FECHA_INICIO, si no la crea
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_FECHA_INICIO", "INT UNSIGNED NOT NULL DEFAULT 0");
        if (!$ret) {
            print STDERR "Error creando columna ART.ART_FECHA_INICIO [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        } elsif ($ret == 1) {
            # se agrego columna nueva, se necesita poblar
            my $sql = "update ART set ART_FECHA_INICIO = ART_FECHAP where ART_FECHAP <> '' and ART_FECHAP <> '99999999' and ART_FECHA_INICIO = 0";
            my $salida = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql);
            if ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr) {
                print STDERR "Error al actualizar tabla de ART [$sql][".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }
            # para poblar los casos de fechap 99999999
            $sql = "update ART set ART_FECHA_INICIO = CONVERT(SUBSTR(ART_ID, 1, 8),UNSIGNED INTEGER) where ART_FECHA_INICIO = 0;";
            $salida = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql);
            if ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr) {
                print STDERR "Error al actualizar tabla de ART [$sql][".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }
        }
        &update_progress($status_file, int($ready+$prontus_percent*52));

        # Valida si existe la columna ART_S3, si no la crea
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_S3", "TINYINT UNSIGNED NOT NULL DEFAULT 0");
        if (!$ret) {
            print STDERR "Error creando columna ART.ART_S3 [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }
        &update_progress($status_file, int($ready+$prontus_percent*56));

        # Valida si existe la columna ART_TOTAL_SIZE, si no la crea
        $ret = glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_TOTAL_SIZE", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
        if (!$ret) {
            print STDERR "Error creando columna ART.ART_TOTAL_SIZE [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        } elsif ($ret) {
            # Valida si existe la columna ART_DISK_SIZE, si no la crea
            $ret = glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_DISK_SIZE", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna ART.ART_DISK_SIZE [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }

            # Valida si existe la columna ART_MEDIA_SIZE, si no la crea
            $ret = glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_MEDIA_SIZE", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna ART.ART_MEDIA_SIZE [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }

            # Valida si existe la columna ART_ASSET_SIZE, si no la crea
            $ret = glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_ASSET_SIZE", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna ART.ART_ASSET_SIZE [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }

            # Valida si existe la columna ART_IMAG_SIZE, si no la crea
            $ret = glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_IMAG_SIZE", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna ART.ART_IMAG_SIZE [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }

            # Valida si existe la columna ART_S3_MEDIA_SIZE, si no la crea
            $ret = glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_S3_MEDIA_SIZE", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna ART.ART_S3_MEDIA_SIZE [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }

            # Valida si existe la columna ART_S3_ASSET_SIZE, si no la crea
            $ret = glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_S3_ASSET_SIZE", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
            if (!$ret) {
                print STDERR "Error creando columna ART.ART_S3_ASSET_SIZE [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }

            # se agrego columna nueva, se necesita poblar
            my $sql = 'select count(*) from ART where ART_TOTAL_SIZE=0';
            my $count;
            my $salida = glib_dbi_03::ejecutar_sql_bind($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \($count));
            $salida->fetch;
            $salida->finish;
            # si hay articulos con tamaño = 0 hay que indexar los que faltan
            if ($count) {
                my $cmd = "$path_cgicpn/utils/prontus_art_size_index.pl $prontus_varglb::PRONTUS_ID >/dev/null 2>&1 &";
                print STDERR "[" . glib_hrfec_03::get_dtime_pack4() . "]$cmd\n";
                system $cmd;
            }
        }
        # exit;
        &update_progress($status_file, int($ready+$prontus_percent*59));

        # Valida si existe la columna ART_MODTIME, si no la crea
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_MODTIME", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
        if (!$ret) {
            print STDERR "Error creando columna ART.ART_MODTIME [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        } elsif ($ret) {
            # se agrego columna nueva, se necesita poblar
            my $sql = 'select count(*) from ART where ART_MODTIME = 0';
            my $count;
            my $salida = &glib_dbi_03::ejecutar_sql_bind($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql, \($count));
            $salida->fetch;
            $salida->finish;

            # si hay  articulos con modtime = 0 hay que indexar los que faltan
            if ($count) {
                my $cmd = "$path_cgicpn/utils/prontus_art_modtime_index.pl $prontus_varglb::PRONTUS_ID >/dev/null 2>&1 &";
                print STDERR "[" . &glib_hrfec_03::get_dtime_pack4() . "]$cmd\n";
                system $cmd;
            }
        }
        &update_progress($status_file, int($ready+$prontus_percent*62));

        # Valida si existe la columna ART_S3_SIZE, si no la crea
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_S3_SIZE", "BIGINT UNSIGNED NOT NULL DEFAULT 0");
        if (!$ret) {
            print STDERR "Error creando columna ART.ART_S3_SIZE [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }
        &update_progress($status_file, int($ready+$prontus_percent*66));

        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_FECHA_FIN", "INT UNSIGNED NOT NULL DEFAULT 0");
        if (!$ret) {
            print STDERR "Error creando columna ART.ART_FECHA_FIN [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        } elsif ($ret == 1) {
            # se agrego columna nueva, se necesita poblar
            my $sql = "update ART set ART_FECHA_FIN = ART_FECHAP where ART_FECHAP <> '' and ART_FECHAP <> '99999999' and ART_FECHA_FIN = 0";
            my $salida = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql);
            if ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr) {
                print STDERR "Error al actualizar tabla de ART [$sql][".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }
            # para poblar los casos de fechap 99999999
            $sql = "update ART set ART_FECHA_FIN = CONVERT(SUBSTR(ART_ID, 1, 8),UNSIGNED INTEGER) where ART_FECHA_FIN = 0;";
            $salida = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql);
            if ($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr) {
                print STDERR "Error al actualizar tabla de ART [$sql][".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
            }
        }
        &update_progress($status_file, int($ready+$prontus_percent*70));

        # Valida si existe la columna ART_INDEXAR, si no la crea
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_INDEXAR", "TINYINT UNSIGNED NOT NULL DEFAULT 1");
        if (!$ret) {
            print STDERR "Error creando columna ART.ART_INDEXAR [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }
        &update_progress($status_file, int($ready+$prontus_percent*74));

        # Valida si existe la columna ART_PRIORIZAR, si no la crea
        $ret = &glib_dbi_03::check_table_column($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} , "ART", "ART_PRIORIZAR", "TINYINT UNSIGNED NOT NULL DEFAULT 0");
        if (!$ret) {
            print STDERR "Error creando columna ART.ART_PRIORIZAR [".$prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->errstr."]\n";
        }

        # cambiamos tipos de columnas de BD
        foreach my $column (@columnas_bd) {
            my ($res, $nom, $type, $null, $key, $default, $extra) = &glib_dbi_03::get_table_column_def($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $$column{'table'}, $$column{'column'});
            # columna existe y es char
            if ($res && $type =~ /char\(/) {
                # columna tipo char la convertimos a numero
                my $sql = "ALTER TABLE $$column{'table'} MODIFY COLUMN $$column{'column'} $$column{'coldef'}";
                my $salida = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql);
                $salida->finish;
            }
        }

        # agregamos indices a tablas de prontus
        foreach my $column (@index_tables) {
            my $exist = glib_dbi_03::check_index_table($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $$column{'table'}, $$column{'column'});

            if (!$exist) {
                # indice no existe, lo agregamos
                my $sql_index = "alter table $$column{'table'} add index ($$column{'column'})";
                my $salida = &glib_dbi_03::ejecutar_sql($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}, $sql_index);
                $salida->finish;
            }
        }

        &update_progress($status_file, int($ready+$prontus_percent*82));
        # terminan modificaciones a BD

        # ajustes a la configuracion de F4-F5 elimina variables que son equivalentes
        my $path_cfg = "$prontus_varglb::DIR_SERVER/$prontus_varglb::PRONTUS_ID/cpan/$prontus_varglb::PRONTUS_ID-var.cfg";

        if ($prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'FRIENDLY_URLS_VERSION'} eq '4') {
            # Lee archivo de configuracion.
            my $buffer = &glib_fildir_03::read_file($path_cfg);

            # quitamos variables correspondientes solo a F5
            $buffer =~ s/FRIENDLY_V5_INCLUDE_VIEW_NAME\s*=\s*["'](SI|NO)["']\n//sg;
            $buffer =~ s/FRIENDLY_V5_EXCLUDE_FID\s*=\s*["'][^'"]+["']//sg;

            # renombra variables a nueva variable comun
            $buffer =~ s/FRIENDLY_V4_EXCLUDE_FID/FRIENDLY_EXCLUDE_FID/g;
            $buffer =~ s/FRIENDLY_V4_INCLUDE_VIEW_NAME/FRIENDLY_INCLUDE_VIEW_NAME/g;

            &glib_fildir_03::write_file($path_cfg, $buffer);
        } elsif ($prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'FRIENDLY_URLS_VERSION'} eq '5') {
            # Lee archivo de configuracion.
            my $buffer = &glib_fildir_03::read_file($path_cfg);

            # quitamos variables correspondientes solo a F4
            $buffer =~ s/FRIENDLY_V4_INCLUDE_VIEW_NAME\s*=\s*["'](SI|NO)["']\n//g;
            $buffer =~ s/FRIENDLY_V4_EXCLUDE_FID\s*=\s*["'][^'"]+["']\n//g;

            # renombra variables a nueva variable comun
            $buffer =~ s/FRIENDLY_V5_EXCLUDE_FID/FRIENDLY_EXCLUDE_FID/g;
            $buffer =~ s/FRIENDLY_V5_INCLUDE_VIEW_NAME/FRIENDLY_INCLUDE_VIEW_NAME/g;

            &glib_fildir_03::write_file($path_cfg, $buffer);
        }

        # ajustes a la configuracion, cambia VARNISH_ por CACHE_
        $path_cfg = "$prontus_varglb::DIR_SERVER/$prontus_varglb::PRONTUS_ID/cpan/$prontus_varglb::PRONTUS_ID-cache.cfg";
        my $buffer = &glib_fildir_03::read_file($path_cfg);

        # renombra variables a nuevo nombre
        $buffer =~ s/VARNISH_GLOBAL_PURGE/CACHE_GLOBAL_PURGE/g;
        $buffer =~ s/VARNISH_SERVER_NAME/CACHE_SERVER_NAME/g;

        &glib_fildir_03::write_file($path_cfg, $buffer);

        &update_progress($status_file, int($ready+$prontus_percent*86));

        # este metodo recarga la configuracion del prontus_id indicado
        my $msg_error = &lib_prontus::generaJsonProntus($prontus_varglb::PRONTUS_ID);
        if ($msg_error ne '') {
            print STDERR "$msg_error\n";
            next;
        }

        &update_progress($status_file, int($ready+$prontus_percent*88));

        # Actualiza el embed.html de prontus/front, reemplaza ##timestamp##
        my $path_embed_tpl = "$prontus_varglb::DIR_SERVER/prontus/cpan/plantillas/front/embed_tpl.html";
        my $path_embed = "$prontus_varglb::DIR_SERVER/prontus/front/embed.html";
        my $buffer_embed = &glib_fildir_03::read_file($path_embed_tpl);
        my $timestamp = time();
        $buffer_embed =~ s/##timestamp##/$timestamp/g;
        &glib_fildir_03::write_file($path_embed, $buffer_embed);

        &update_progress($status_file, int($ready+$prontus_percent*90));

        &lib_tags::generar_json($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        &update_progress($status_file, int($ready+$prontus_percent*94));

        &lib_tax::generar_json($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});
        &update_progress($status_file, int($ready+$prontus_percent*98));

        &lib_multitag::generar_json($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});

        &lib_multitag::generar_json_fid($prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID});

        # desconectamos la bd de prontus
        $prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID}->disconnect;
        $prontus_varglb::BD_CONN{$prontus_varglb::PRONTUS_ID} = undef;

        &update_progress($status_file, int($ready+$prontus_percent*100));

        print STDERR "\n\n";
    }
    &glib_fildir_03::write_file($status_file, '{"status": 1, "progress":100, "msg":"terminado"}');

    glib_fildir_03::borra_dir("$prontus_varglb::DIR_SERVER/prontus/data") if (-d "$prontus_varglb::DIR_SERVER/prontus/data");
    glib_fildir_03::borra_dir("$prontus_varglb::DIR_SERVER/prontus/ejemplos") if (-d "$prontus_varglb::DIR_SERVER/prontus/ejemplos");

    &glib_fildir_03::write_file("$prontus_varglb::DIR_SERVER/prontus/cpan/data/prontus_updated.txt", $prontus_varglb::VERSION_PRONTUS);
}

sub update_progress {
    my ($status_file, $percent) = @_;
    glib_fildir_03::write_file($status_file, '{"status": 1, "progress":'. $percent .', "msg":"procesando"}');
}
# ---------------------------------------------------------------
# funcion para capturar las señales INT y TERM y logearlas
sub signal_catch {
    print STDERR  "Terminado por signal @_\n";
    exit(0);
}

END {
    if ($ERROR ne '') {
        my $status_file = "$prontus_varglb::DIR_SERVER/prontus/cpan/data/prontus_updated.json";
        &glib_fildir_03::write_file($status_file, '{"status": 0, "progress":0, "msg":"'.$ERROR.'"}');
        print STDERR "$ERROR\n";
    }
    unlink "$prontus_varglb::DIR_SERVER/prontus/cpan/data/_login.block";
}
