#!/bin/bash

# ======================================================================
# File:        functions
# Author:      Charlie Martínez® <cmartinez@quirinux.org>
# License:     https://www.gnu.org/licenses/gpl-2.0.txt
# Purpose:     Collection of functions
# Distro:      Quirinux 2.0
# ======================================================================

#
# Collection of Quirinux 2.0 functions required for the execution  
# of its "crearmaster" and "creariso" scripts.  
#
# Copyright (c) 2019-2025 Charlie Martínez. All Rights Reserved.  
# License: https://www.gnu.org/licenses/gpl-2.0.txt  
# Authorized and unauthorized uses of the Quirinux trademark:  
# See https://www.quirinux.org/aviso-legal  
#

# ======================================================================
# Variables
# ======================================================================

	source "/opt/isocreate/var_distro" # Distribution variables

# ======================================================================
# Funciones locales
# ======================================================================

function _quit() {
    # Function to exit
    clear
    exit 0
}

function _rootcheck() {	
	# Check if the user has administrator privileges
	if [ "$EUID" -ne 0  ]; then
		echo ''
		echo "Este script debe ejecutarse con permisos de root."
		echo 'Puedes intentarlo con "sudo" tuusuario, "sudo su" o "su root".'
		echo ''
		exit 1
	fi	
}

# Comprobación de Internet robusta: no depende solo de ICMP/DNS (un "ping" a
# google.com falla en sistemas recién instalados, con ICMP filtrado o DNS sin
# arrancar). Basta con que un método funcione.
_hayInternet() {
    local url ip
    if command -v curl >/dev/null 2>&1; then
        for url in http://connectivity-check.ubuntu.com http://www.gstatic.com/generate_204 https://repo.quirinux.org; do
            curl -s -o /dev/null --connect-timeout 4 --max-time 8 "$url" && return 0
        done
    elif command -v wget >/dev/null 2>&1; then
        for url in http://connectivity-check.ubuntu.com http://www.gstatic.com/generate_204 https://repo.quirinux.org; do
            wget -q -O /dev/null --timeout=6 --tries=1 "$url" && return 0
        done
    fi
    for ip in repo.quirinux.org 1.1.1.1 8.8.8.8 9.9.9.9; do
        timeout 4 bash -c "exec 3<>/dev/tcp/$ip/443" >/dev/null 2>&1 && return 0
    done
    for ip in 1.1.1.1 8.8.8.8 google.com; do
        ping -c 1 -W 3 -q "$ip" >/dev/null 2>&1 && return 0
    done
    return 1
}

function _internet() {
	# Check if there is an active internet connection
	if ! _hayInternet; then
		echo "ERROR: Este programa require conexión a internet."
		exit 1
	fi        
}

function _update() {
    # Detect the package manager and update the system
    if command -v apt-get &>/dev/null; then
        apt-get update && apt-get upgrade -y
    elif command -v dnf &>/dev/null; then
        dnf update -y
    elif command -v yum &>/dev/null; then
        yum update -y
    else
        echo "No se encontró un gestor de paquetes compatible" >&2
        exit 1
    fi    
}


function _depends() {
	# Install required packages and handle dependencies
    TMP_DIR="/tmp/repo"
    mkdir -p "$TMP_DIR"
    
    get_latest_version() {
        local location=$1
        # Check if location is a URL or a local directory
        if [[ $location =~ ^https?:// ]]; then
            wget -qO- "$location" | grep -oP "[a-zA-Z0-9._-]+\.(deb|rpm)" | sort -V | tail -n 1
        else
            find "$location" -type f \( -name "*.deb" -o -name "*.rpm" \) | sort -V | tail -n 1 | xargs -I{} basename {}
        fi
    }
    
    if [ ! -e /opt/isocreate/requisitos/ok-dependencias ]; then
        _update
        
        # Define the required packages
        BASE_PACKAGES=(wget git spice-vdagent dialog)
        
        # Install required packages based on the package manager
        if command -v apt &>/dev/null; then
            for pkg in "${BASE_PACKAGES[@]}"; do
                if ! dpkg -l | grep -qw "$pkg"; then
                    apt install -y "$pkg"
                fi
            done
        elif command -v dnf &>/dev/null; then
            for pkg in "${BASE_PACKAGES[@]}"; do
                if ! dnf list installed "$pkg" &>/dev/null; then
                    dnf install -y "$pkg"
                fi
            done
        elif command -v yum &>/dev/null; then
            for pkg in "${BASE_PACKAGES[@]}"; do
                if ! yum list installed "$pkg" &>/dev/null; then
                    yum install -y "$pkg"
                fi
            done
        else
            echo "No se encontró un gestor de paquetes compatible" >&2
            exit 1
        fi
        
        # Install additional dependencies from specified locations
        for location in "${DISTRO_DEPENDS_LOCATION[@]}"; do
            latest_package=$(get_latest_version "$location")
            
            if [[ -n "$latest_package" ]]; then
                if [[ $location =~ ^https?:// ]]; then
                    wget --no-check-certificate "$location$latest_package" -O "$TMP_DIR/$latest_package"
                else
                    cp "$location/$latest_package" "$TMP_DIR/"
                fi
                
                # Install downloaded packages
                if [[ "$latest_package" == *.deb ]]; then
                    apt install -y "$TMP_DIR/$latest_package"
                elif [[ "$latest_package" == *.rpm ]]; then
                    if command -v dnf &>/dev/null; then
                        dnf install -y "$TMP_DIR/$latest_package"
                    elif command -v yum &>/dev/null; then
                        yum install -y "$TMP_DIR/$latest_package"
                    fi
                fi
            fi
        done
        
        mkdir -p /opt/isocreate/requisitos/
        touch /opt/isocreate/requisitos/ok-dependencias
    fi
}

function _lang() {	
	 # Configure language settings
	if [ ! -e /opt/isocreate/requisitos/ok-lang ]; then
		
	if [ ! -e /usr/share/locale/locale.alias ]; then
	touch /usr/share/locale/locale.alias
	fi
    
    idiomas=("es_ES.UTF-8" "en_US.UTF-8" "fr_FR.UTF-8" "de_DE.UTF-8" "it_IT.UTF-8" "gl_ES.UTF-8" "pt_PT.UTF-8")

   # Configure each language
    for idioma in "${idiomas[@]}"; do
        # Check if the configuration already exists
        if ! locale -a | grep -q "$idioma"; then
            sudo locale-gen $idioma
            echo "Configuración de $idioma completa."
        fi
        if [ "$idioma" == "pt_PT.UTF-8" ]; then
            break # Exit the loop when it reaches pt_PT.UTF-8
        fi
    done

    # Set the default language
    sudo update-locale LANG="es_ES.UTF-8"
    
    touch /opt/isocreate/requisitos/ok-lang
    
    fi
}

function _verif_path() {
	# Function to check if the user's DISTRO_PATH exists
    if [ ! -d "$DISTRO_PATH" ]; then
        echo "ERROR: Comando exclusivo para ser utilizado en ${DISTRO_NAME^} Master."
        exit 1
	fi
}
