#\!/bin/bash # This module contains utility functions # Text colors GREEN='\033[0;32m' YELLOW='\033[1;33m' RED='\033[0;31m' NC='\033[0m' # No Color # Function to check if a command exists command_exists() { command -v "$1" &> /dev/null } # Function to check if running as root check_root() { if [ "$(id -u)" -ne 0 ]; then echo -e "${RED}This script must be run as root or with sudo${NC}" exit 1 fi } # Function to get the system's IP address get_ip_address() { local ip="" if command_exists ip; then ip=$(ip -4 addr show scope global | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -n 1) elif command_exists hostname; then ip=$(hostname -I | awk '{print $1}') elif command_exists ifconfig; then ip=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | head -n 1) fi echo "$ip" } # Function to check if a service is installed service_exists() { local service_name=$1 if [ -f "/etc/systemd/system/$service_name.service" ]; then return 0 # Service exists else return 1 # Service does not exist fi } # Function to create directory if it doesn't exist ensure_dir_exists() { local dir_path=$1 if [ \! -d "$dir_path" ]; then mkdir -p "$dir_path" echo "Created directory: $dir_path" fi } # Function to verify file permissions verify_permissions() { local file_path=$1 local user=$2 # If user is not specified, use current user if [ -z "$user" ]; then user=$(whoami) fi # Check if file exists if [ \! -f "$file_path" ]; then echo "File does not exist: $file_path" return 1 fi # Check ownership local owner=$(stat -c '%U' "$file_path") if [ "$owner" \!= "$user" ]; then echo "Changing ownership of $file_path to $user" sudo chown "$user" "$file_path" fi # Ensure file is executable if it's a script if [[ "$file_path" == *.sh ]]; then if [ \! -x "$file_path" ]; then echo "Making $file_path executable" chmod +x "$file_path" fi fi return 0 }