#!/usr/bin/env bash # Common utility functions for provisioning scripts # Colors for output RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' # No Color # Logging functions log_info() { echo -e "${BLUE}[INFO]${NC} $1" } log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1" } log_warn() { echo -e "${YELLOW}[WARN]${NC} $1" } log_error() { echo -e "${RED}[ERROR]${NC} $1" >&2 } # Platform detection detect_os() { case "$OSTYPE" in darwin*) echo "macos" ;; linux*) if [ -f /etc/arch-release ]; then echo "arch" elif [ -f /etc/os-release ]; then # Check for specific distributions . /etc/os-release case "$ID" in elementary|elementaryos) echo "debian" # elementaryOS is Ubuntu-based ;; ubuntu|debian|pop|linuxmint) echo "debian" ;; *) # Fallback to debian_version check if [ -f /etc/debian_version ]; then echo "debian" else echo "linux" fi ;; esac elif [ -f /etc/debian_version ]; then echo "debian" else echo "linux" fi ;; *) echo "unknown" ;; esac } # Check if command exists command_exists() { command -v "$1" >/dev/null 2>&1 } # Check if running on macOS is_macos() { [ "$(detect_os)" = "macos" ] } # Check if running on Debian/Ubuntu is_debian() { [ "$(detect_os)" = "debian" ] } # Check if running on Arch is_arch() { [ "$(detect_os)" = "arch" ] } # Check if running on Linux is_linux() { [[ "$OSTYPE" == "linux"* ]] } # Check if running on elementary OS is_elementary() { if [ -f /etc/os-release ]; then . /etc/os-release [[ "$ID" == "elementary" || "$ID" == "elementaryos" ]] else return 1 fi } # Create directory if it doesn't exist ensure_dir() { if [ ! -d "$1" ]; then mkdir -p "$1" log_info "Created directory: $1" fi } # Create symlink, backing up existing file if needed safe_symlink() { local source="$1" local target="$2" if [ -L "$target" ]; then # It's already a symlink if [ "$(readlink "$target")" = "$source" ]; then log_info "Symlink already exists: $target -> $source" return 0 else log_warn "Replacing existing symlink: $target" rm "$target" fi elif [ -f "$target" ] || [ -d "$target" ]; then # File or directory exists, back it up local backup="${target}.backup.$(date +%Y%m%d_%H%M%S)" log_warn "Backing up existing file to: $backup" mv "$target" "$backup" fi ln -sf "$source" "$target" log_success "Created symlink: $target -> $source" } # Execute command with sudo if not running as root maybe_sudo() { if [ "$EUID" -ne 0 ]; then sudo "$@" else "$@" fi } # Check if script is being sourced or executed is_sourced() { [ "${BASH_SOURCE[0]}" != "${0}" ] } # Export OS detection for use in other scripts export OS_TYPE=$(detect_os)