#!/usr/bin/env bash
# Common shell functions for FetchML scripts
# Source this file in other scripts: source "$(dirname "$0")/lib/common.sh"

# Colors for output
export BOLD='\033[1m'
export GREEN='\033[0;32m'
export BLUE='\033[0;34m'
export YELLOW='\033[0;33m'
export RED='\033[0;31m'
export NC='\033[0m'

###################
# Logging functions
###################

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}✓${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

log_step() {
    local step=$1
    local total=$2
    local message=$3
    echo -e "${BLUE}[$step/$total]${NC} $message"
}

print_header() {
    local title=$1
    echo ""
    echo -e "${BOLD}=== $title ===${NC}"
    echo ""
}

###################
# System detection
###################

detect_distro() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        export DISTRO=$ID
        export DISTRO_VERSION=$VERSION_ID
    elif [ -f /etc/redhat-release ]; then
        export DISTRO="rhel"
        export DISTRO_VERSION="unknown"
    else
        export DISTRO="unknown"
        export DISTRO_VERSION="unknown"
    fi
    
    # Detect package manager
    if command -v dnf &>/dev/null; then
        export PKG_MANAGER="dnf"
    elif command -v yum &>/dev/null; then
        export PKG_MANAGER="yum"
    elif command -v apt-get &>/dev/null; then
        export PKG_MANAGER="apt"
    elif command -v pacman &>/dev/null; then
        export PKG_MANAGER="pacman"
    elif command -v zypper &>/dev/null; then
        export PKG_MANAGER="zypper"
    else
        log_warn "No known package manager found"
        export PKG_MANAGER="unknown"
    fi
    
    log_info "Detected: $DISTRO $DISTRO_VERSION (using $PKG_MANAGER)"
}

###################
# Utility functions
###################

check_command() {
    local cmd=$1
    local install_hint=$2
    
    if ! command -v "$cmd" &>/dev/null; then
        log_error "$cmd not found"
        if [ -n "$install_hint" ]; then
            log_info "Install with: $install_hint"
        fi
        return 1
    fi
    return 0
}

check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "This script must be run with sudo"
        exit 1
    fi
}

confirm() {
    local prompt=$1
    local default=${2:-n}
    
    if [ "$default" = "y" ]; then
        read -p "$prompt [Y/n]: " -n 1 -r
    else
        read -p "$prompt [y/N]: " -n 1 -r
    fi
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        return 0
    else
        return 1
    fi
}

###################
# Firewall management
###################

setup_firewall() {
    local port=$1
    local comment=${2:-"FetchML"}
    
    if command -v firewall-cmd &>/dev/null; then
        # RHEL/Rocky/Fedora (firewalld)
        sudo firewall-cmd --permanent --add-port="${port}/tcp" >/dev/null 2>&1
        log_success "Firewall rule added (firewalld): ${port}/tcp"
        return 0
    elif command -v ufw &>/dev/null; then
        # Ubuntu/Debian (ufw)
        sudo ufw allow "${port}/tcp" comment "$comment" >/dev/null 2>&1
        log_success "Firewall rule added (ufw): ${port}/tcp"
        return 0
    else
        log_warn "No firewall detected. Manually open port ${port}/tcp"
        return 1
    fi
}

reload_firewall() {
    if command -v firewall-cmd &>/dev/null; then
        sudo firewall-cmd --reload >/dev/null 2>&1
        log_success "Firewall reloaded (firewalld)"
    elif command -v ufw &>/dev/null; then
        sudo ufw reload >/dev/null 2>&1 || true
        log_success "Firewall reloaded (ufw)"
    fi
}

###################
# File/directory management
###################

create_dir() {
    local dir=$1
    local owner=${2:-$USER}
    local group=${3:-$(id -gn)}
    
    sudo mkdir -p "$dir"
    sudo chown "$owner:$group" "$dir"
    sudo chmod 755 "$dir"
    log_success "Created: $dir"
}

check_service() {
    local service=$1
    
    if systemctl list-unit-files | grep -q "^${service}"; then
        return 0
    else
        return 1
    fi
}
