#!/bin/sh
set -eu

REPO_URL="${REPO_URL:-https://github.com/jdansak/common_playbooks.git}"
PLAYBOOKS="${PLAYBOOKS:-tools languages interface}"

info()  { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
warn()  { printf '\033[1;33m==>\033[0m %s\n' "$*"; }
error() { printf '\033[1;31mError:\033[0m %s\n' "$*" >&2; exit 1; }

# Resolve the non-root target user when invoked via `sudo sh`
if [ "$(id -u)" -eq 0 ] && [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != "root" ]; then
  TARGET_USER="$SUDO_USER"
  TARGET_HOME="$(eval printf '%s' "~$TARGET_USER")"
  run_as_user() {
    sudo -u "$TARGET_USER" -H "$@"
  }
else
  TARGET_USER="$(id -un)"
  TARGET_HOME="$HOME"
  run_as_user() {
    "$@"
  }
fi

PLAYBOOKS_DIR="${PLAYBOOKS_DIR:-$TARGET_HOME/common_playbooks}"
OS="$(uname -s)"

case "$OS" in
  Darwin)
    info "Detected macOS (Darwin) for user $TARGET_USER"

    if ! xcode-select -p >/dev/null 2>&1; then
      info "Installing Xcode Command Line Tools..."
      xcode-select --install || true
      warn "Complete the Xcode Command Line Tools prompt, then press Enter to continue..."
      read -r _
    fi

    if ! run_as_user sh -c 'command -v brew >/dev/null 2>&1 || [ -x /opt/homebrew/bin/brew ] || [ -x /usr/local/bin/brew ]'; then
      info "Installing Homebrew..."
      run_as_user env NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    fi

    info "Ensuring git and ansible are installed via Homebrew..."
    run_as_user /bin/sh -c '
      if [ -x /opt/homebrew/bin/brew ]; then eval "$(/opt/homebrew/bin/brew shellenv)"
      elif [ -x /usr/local/bin/brew ]; then eval "$(/usr/local/bin/brew shellenv)"
      fi
      command -v git >/dev/null 2>&1 && command -v ansible-playbook >/dev/null 2>&1 || brew install git ansible
    '
    ;;

  Linux)
    if [ ! -r /etc/os-release ]; then
      error "Cannot detect Linux distribution (/etc/os-release not found)."
    fi
    # shellcheck disable=SC1091
    . /etc/os-release
    DISTRO_ID="${ID:-}"
    DISTRO_LIKE="${ID_LIKE:-}"

    case " $DISTRO_ID $DISTRO_LIKE " in
      *" ubuntu "*|*" debian "*)
        info "Detected Debian/Ubuntu ($DISTRO_ID)"
        if [ "$(id -u)" -eq 0 ]; then
          apt-get update
          apt-get install -y git ansible curl
        else
          sudo apt-get update
          sudo apt-get install -y git ansible curl
        fi
        ;;
      *" arch "*)
        info "Detected Arch Linux ($DISTRO_ID)"
        if [ "$(id -u)" -eq 0 ]; then
          pacman -Syu --noconfirm --needed git ansible curl
        else
          sudo pacman -Syu --noconfirm --needed git ansible curl
        fi
        ;;
      *)
        error "Unsupported Linux distribution: ${DISTRO_ID:-unknown}. Supported: Debian/Ubuntu, Arch Linux."
        ;;
    esac
    ;;

  *)
    error "Unsupported OS: $OS. Supported: macOS (Darwin), Debian/Ubuntu, Arch Linux."
    ;;
esac

if [ -d "$PLAYBOOKS_DIR/.git" ]; then
  info "Updating existing repo in $PLAYBOOKS_DIR..."
  run_as_user git -C "$PLAYBOOKS_DIR" pull --ff-only
else
  info "Cloning common_playbooks into $PLAYBOOKS_DIR..."
  run_as_user git clone "$REPO_URL" "$PLAYBOOKS_DIR"
fi

for pb in $PLAYBOOKS; do
  PB_PATH="$PLAYBOOKS_DIR/$pb/playbook.yml"
  if [ -f "$PB_PATH" ]; then
    info "Running $pb playbook..."
    if [ "$OS" = "Darwin" ]; then
      run_as_user /bin/sh -c '
        if [ -x /opt/homebrew/bin/brew ]; then eval "$(/opt/homebrew/bin/brew shellenv)"
        elif [ -x /usr/local/bin/brew ]; then eval "$(/usr/local/bin/brew shellenv)"
        fi
        exec ansible-playbook "$1" -c local -i "localhost,"
      ' _ "$PB_PATH"
    else
      if run_as_user sudo -n true 2>/dev/null; then
        run_as_user ansible-playbook "$PB_PATH" -c local -i "localhost,"
      else
        run_as_user ansible-playbook "$PB_PATH" -c local -i "localhost," -K
      fi
    fi
  else
    warn "Skipping unknown playbook: $PB_PATH"
  fi
done

info "Workstation setup complete! Restart your shell (or run 'exec \$SHELL -l') to load updated PATH and aliases."
