#!/usr/bin/env sh set -eu METHOD="auto" # auto|pkg|pip PIP_USER="--user" usage() { cat <<'EOF' Usage: install-ansible.sh [--method auto|pkg|pip] [--pip-user|--pip-system] EOF } while [ $# -gt 0 ]; do case "$1" in --method) METHOD="${2:-}"; shift 2 ;; --pip-user) PIP_USER="--user"; shift 1 ;; --pip-system) PIP_USER=""; shift 1 ;; -h|--help) usage; exit 0 ;; *) echo "Unknown arg: $1" >&2; usage; exit 1 ;; esac done have() { command -v "$1" >/dev/null 2>&1; } as_root() { if [ "$(id -u)" -eq 0 ]; then sh -c "$*" elif have sudo; then sudo sh -c "$*" else echo "ERROR: need root or sudo: $*" >&2 exit 1 fi } install_pkg() { # macOS if [ "$(uname -s)" = "Darwin" ]; then if have brew; then brew install ansible return 0 fi echo "ERROR: Homebrew not found. Install brew first, or use --method pip." >&2 return 1 fi # Linux package managers (prefer official repos) if have apt-get; then as_root "apt-get update -y && apt-get install -y ansible" return 0 fi if have dnf; then as_root "dnf install -y ansible" return 0 fi if have yum; then as_root "yum install -y ansible" return 0 fi if have zypper; then as_root "zypper -n install ansible" return 0 fi if have pacman; then as_root "pacman -Sy --noconfirm ansible" return 0 fi if have apk; then as_root "apk add --no-cache ansible" return 0 fi return 1 } install_pip() { if have python3; then if have pip3; then pip3 install $PIP_USER ansible return 0 fi python3 -m ensurepip >/dev/null 2>&1 || true python3 -m pip install --upgrade pip >/dev/null 2>&1 || true python3 -m pip install $PIP_USER ansible return 0 fi echo "ERROR: python3 not found; cannot install via pip." >&2 return 1 } # ---- main if [ "$METHOD" = "pkg" ]; then install_pkg || { echo "Package install failed. Try --method pip" >&2; exit 1; } elif [ "$METHOD" = "pip" ]; then install_pip else # auto: try package manager first, then pip fallback install_pkg || install_pip fi # Basic verification if have ansible; then echo "Ansible installed: $(ansible --version | head -n 1)" else echo "WARNING: install completed but 'ansible' not found on PATH." >&2 exit 2 fi