#!/bin/bash # # Script: standardize_scripts.sh # Description: Estandariza los encabezados y estructura de los scripts Bash # Created: $(date +"%Y/%m/%d %H:%M:%S") # Modified: $(date +"%Y/%m/%d %H:%M:%S") # [Author] Cortana Rosero One # [Generated] Created by Claude Code (claude-3-7-sonnet-20250219) # # Derechos de Autor (C) [2025] [Mauro Rosero P. ] # # Este programa es software libre: usted puede redistribuirlo y/o modificarlo # bajo los términos de la Licencia Pública Affero General de GNU tal como # lo publica la Free Software Foundation, ya sea la versión 3 de la licencia, # o (a su elección) cualquier versión posterior. # # Este programa se distribuye con la esperanza de que sea útil, # pero SIN NINGUNA GARANTÍA; sin siquiera la garantía implícita de # COMERCIABILIDAD o IDONEIDAD PARA UN PROPÓSITO PARTICULAR. Consulte la # Licencia Pública Affero General de GNU para obtener más detalles. # # Debería haber recibido una copia de la Licencia Pública Affero General # junto con este programa. Si no la recibió, consulte . # Configuración inicial SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # Leer DEVSPATH desde el archivo de configuración o usar "devs" por defecto if [ -f "$SCRIPT_DIR/config/devspath.dat" ]; then DEVSPATH=$(cat "$SCRIPT_DIR/config/devspath.dat") else DEVSPATH="devs" fi BIN_HOME="$HOME/$DEVSPATH" BIN_BASE="bin" BIN_LIBS="lib" BIN_MESG="msg" BIN_CFGS="config" # CHECK SHELL LANGUAGE BIN_LANG=${LANG:0:2} # Importar bibliotecas necesarias source "${BIN_HOME}/${BIN_BASE}/${BIN_LIBS}/base.lib" source "${BIN_HOME}/${BIN_BASE}/${BIN_LIBS}/console.lib" # Cargar mensajes en el idioma del sistema o español por defecto load_messages "${BIN_HOME}/${BIN_BASE}" "${BIN_MESG}" "${BIN_LANG}" "head" # Variables globales title="${head_000} ${head_002} - ${head_002}" apps_title="${head_000} - ${projmsg_007}" HEADER_TEMPLATE="${BIN_HOME}/${BIN_BASE}/${BIN_CFGS}/bash.head" VARIABLES_TEMPLATE="${BIN_HOME}/${BIN_BASE}/${BIN_CFGS}/bash.variables" DEFAULT_AUTHOR="Mauro Rosero P. " CORTANA_AUTHOR="Cortana Rosero One " CORTANA_GENERATED="Created by Claude Code (claude-3-7-sonnet-20250219)" TODAY=$(date +"%Y/%m/%d %H:%M:%S") # Función para extraer información del script existente extract_script_info() { local script_path="$1" local script_name=$(basename "$script_path") local description="" local created_date="" local modified_date="$TODAY" local author="$DEFAULT_AUTHOR" local generated_by="" # Extraer descripción si existe description=$(grep -A 5 "Description:" "$script_path" | grep "Description:" | sed 's/.*Description: \(.*\)/\1/' | head -1) if [ -z "$description" ]; then # Intentar extraer del comentario antes de la primera función o variable description=$(sed -n '/#.*[Ss]cript/p' "$script_path" | head -1 | sed 's/#.*[Ss]cript[^:]*: \(.*\)/\1/') if [ -z "$description" ]; then description="Script para $script_name" fi fi # Extraer fecha de creación si existe created_date=$(grep -A 10 "Created:" "$script_path" | grep "Created:" | sed 's/.*Created: \(.*\)/\1/' | head -1) if [ -z "$created_date" ]; then created_date="$TODAY" fi # Extraer fecha de modificación si existe mod_date=$(grep -A 10 "Modified:" "$script_path" | grep "Modified:" | sed 's/.*Modified: \(.*\)/\1/' | head -1) if [ ! -z "$mod_date" ]; then modified_date="$mod_date" fi # Extraer autor si existe auth=$(grep -A 10 "\[Author\]" "$script_path" | grep "\[Author\]" | sed 's/.*\[Author\] \(.*\)/\1/' | head -1) if [ ! -z "$auth" ]; then author="$auth" fi # Extraer información de generación si existe gen=$(grep -A 10 "\[Generated\]" "$script_path" | grep "\[Generated\]" | sed 's/.*\[Generated\] \(.*\)/\1/' | head -1) if [ ! -z "$gen" ]; then generated_by="$gen" elif [[ "$author" == *"Cortana"* ]]; then generated_by="$CORTANA_GENERATED" fi # Crear array con la información extraída echo "$script_name|$description|$created_date|$modified_date|$author|$generated_by" } # Función para aplicar la plantilla a un script apply_template() { local script_path="$1" local info="$2" # Separar la información en variables IFS='|' read -r script_name description created_date modified_date author generated_by <<< "$info" # Crear encabezado temporal con la información extraída local temp_header=$(mktemp) cat "$HEADER_TEMPLATE" > "$temp_header" # Reemplazar las variables en la plantilla sed -i "s|\$SCRIPT_NAME|$script_name|g" "$temp_header" sed -i "s|\$DESCRIPTION|$description|g" "$temp_header" sed -i "s|\$CREATED_DATE|$created_date|g" "$temp_header" sed -i "s|\$MODIFIED_DATE|$modified_date|g" "$temp_header" sed -i "s|\$AUTHOR|$author|g" "$temp_header" if [ ! -z "$generated_by" ]; then sed -i "s|\$GENERATED_BY|$generated_by|g" "$temp_header" else # Si no hay información de generación, eliminar esa línea sed -i '/\$GENERATED_BY/d' "$temp_header" fi # Extraer el cuerpo del script (todo excepto el encabezado) local temp_body=$(mktemp) # Encontrar línea después del encabezado (primera línea en blanco después de los comentarios iniciales) local header_end=$(grep -n "^$" "$script_path" | head -1 | cut -d: -f1) if [ -z "$header_end" ]; then header_end=25 # Valor predeterminado si no se encuentra una línea en blanco fi # Extraer el cuerpo del script tail -n +$header_end "$script_path" > "$temp_body" # Crear el nuevo script combinando el encabezado y el cuerpo cat "$temp_header" > "$script_path" echo "" >> "$script_path" # Línea en blanco después del encabezado cat "$temp_body" >> "$script_path" # Limpiar archivos temporales rm -f "$temp_header" "$temp_body" echo "Estandarizado: $script_path" } # Función para estandarizar variables comunes en el script standardize_variables() { local script_path="$1" # Buscar y reemplazar patrones comunes de variables if grep -q "DEVSPATH=" "$script_path"; then # Determinar dónde comienzan las variables local var_line=$(grep -n "DEVSPATH=" "$script_path" | head -1 | cut -d: -f1) local next_section=$(grep -n "^# " "$script_path" | awk -v start="$var_line" '$1 > start {print $1; exit}' | cut -d: -f1) if [ -z "$next_section" ]; then # Si no hay otra sección, buscar la primera función next_section=$(grep -n "^[a-zA-Z_][a-zA-Z0-9_]*().*{" "$script_path" | head -1 | cut -d: -f1) if [ -z "$next_section" ]; then # Si no hay función, usar el final del archivo next_section=$(wc -l "$script_path" | awk '{print $1}') fi fi # Crear un archivo temporal con el contenido antes de las variables local temp_before=$(mktemp) head -n $((var_line - 1)) "$script_path" > "$temp_before" # Crear un archivo temporal con el contenido después de las variables local temp_after=$(mktemp) tail -n +$next_section "$script_path" > "$temp_after" # Crear el nuevo script cat "$temp_before" > "$script_path" cat "$VARIABLES_TEMPLATE" >> "$script_path" echo "" >> "$script_path" # Añadir línea en blanco cat "$temp_after" >> "$script_path" # Limpiar archivos temporales rm -f "$temp_before" "$temp_after" fi # Estandarizar la carga de bibliotecas if ! grep -q "source .*base.lib" "$script_path"; then echo -e "\n# Importar bibliotecas necesarias\nsource \"\${BIN_HOME}/\${BIN_BASE}/\${BIN_LIBS}/base.lib\"" >> "$script_path" fi # Estandarizar la carga de mensajes si aún no existe if ! grep -q "load_messages" "$script_path"; then echo -e "\n# Cargar mensajes en el idioma del sistema o español por defecto\nload_messages \"\${BIN_HOME}/\${BIN_BASE}\" \"\${BIN_MESG}\" \"\${BIN_LANG}\" \"head\"" >> "$script_path" fi # Estandarizar la definición del título si no existe if ! grep -q "title=" "$script_path"; then echo -e "\n# Variables globales\ntitle=\"\${head_000} \${head_002}\"" >> "$script_path" fi } # Función principal main() { dialog_error_box "$title" "${head_info}: ${head_002} $BIN_HOME/$BIN_BASE" # Verificar que existe la plantilla de encabezado if [ ! -f "$HEADER_TEMPLATE" ]; then dialog_error_box "$title" "${head_error}: ${head_nobuild} $HEADER_TEMPLATE" exit 1 fi # Verificar que existe la plantilla de variables if [ ! -f "$VARIABLES_TEMPLATE" ]; then dialog_error_box "$title" "${head_error}: ${head_nodockerfile} $VARIABLES_TEMPLATE" exit 1 fi # Contar scripts a procesar local total_scripts=$(find "$BIN_HOME/$BIN_BASE" -name "*.sh" | wc -l) local current=0 dialog_error_box "${head_info}" "${head_container} $total_scripts" # Recorrer todos los scripts .sh en el directorio bin for script in "$BIN_HOME/$BIN_BASE"/*.sh; do current=$((current + 1)) # Saltar el script actual para evitar problemas if [ "$(basename "$script")" == "$(basename "$0")" ]; then echo "[$current/$total_scripts] ${head_exit}: $(basename "$script")" continue fi echo "[$current/$total_scripts] ${head_info}: $(basename "$script")" # Hacer una copia de seguridad del script cp "$script" "${script}.bak" # Extraer información del script local script_info=$(extract_script_info "$script") # Aplicar la plantilla de encabezado apply_template "$script" "$script_info" # Estandarizar variables y estructura común standardize_variables "$script" echo " ✓ ${head_create}: $(basename "$script")" done dialog_error_box "${head_info}" "${head_builded} $current ${head_container}.\n\n${head_version}.bak" } # Ejecutar función principal main