Newer
Older
ops-toolkit / bootstrap.sh
#!/usr/bin/env bash
# bootstrap.sh -- ops-toolkit entry point
#
# Discovers packs (directories under packs/ containing install-pack.sh) and
# runs the selected pack installers in order, stopping on first failure.
#
# Mutates: only what the selected packs install (each pack states its own
# mutations; every mutation is visible in --dry-run first).
#
# Usage:
#   bash bootstrap.sh --list                 # show available packs
#   bash bootstrap.sh --dry-run --all        # show what would change
#   bash bootstrap.sh --all                  # install every pack
#   bash bootstrap.sh tmux shell             # install named packs only
#
# Exit codes: 0 PROCEED, 1 HOLD (a pack failed), 2 precondition/usage error.
# ASCII + LF.

set -euo pipefail
shopt -s inherit_errexit 2>/dev/null || true
IFS=$'\n\t'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/lib-install.sh
. "$SCRIPT_DIR/lib/lib-install.sh"

usage() {
    sed -n '2,16p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
}

discover_packs() {
    local d
    for d in "$SCRIPT_DIR"/packs/*/; do
        [ -f "${d}install-pack.sh" ] && basename "$d"
    done
}

DRY_RUN=0
LIST_ONLY=0
ALL=0
SELECTED=()

while [ $# -gt 0 ]; do
    case "$1" in
        --list)    LIST_ONLY=1 ;;
        --dry-run) DRY_RUN=1 ;;
        --all)     ALL=1 ;;
        -h|--help) usage; exit 0 ;;
        -*)        fail "unknown option: $1"; usage; exit 2 ;;
        *)         SELECTED+=("$1") ;;
    esac
    shift
done

AVAILABLE=()
while IFS= read -r p; do AVAILABLE+=("$p"); done < <(discover_packs)

if [ "${#AVAILABLE[@]}" -eq 0 ]; then
    fail "no packs found under $SCRIPT_DIR/packs/"
    exit 2
fi

if [ "$LIST_ONLY" = "1" ]; then
    info "available packs:"
    for p in "${AVAILABLE[@]}"; do
        printf '  %-12s %s\n' "$p" \
            "$(head -n1 "$SCRIPT_DIR/packs/$p/README.md" 2>/dev/null | sed 's/^# *//')"
    done
    exit 0
fi

if [ "$ALL" = "1" ]; then
    SELECTED=("${AVAILABLE[@]}")
fi

if [ "${#SELECTED[@]}" -eq 0 ]; then
    fail "no packs selected"
    usage
    exit 2
fi

# Validate selection before running anything (fail early, mutate nothing).
for p in "${SELECTED[@]}"; do
    if [ ! -f "$SCRIPT_DIR/packs/$p/install-pack.sh" ]; then
        fail "unknown pack: $p (try --list)"
        exit 2
    fi
done

export TOOLKIT_DRY_RUN="$DRY_RUN"
[ "$DRY_RUN" = "1" ] && info "DRY-RUN mode: no changes will be made"

for p in "${SELECTED[@]}"; do
    info "==== pack: $p ===="
    if ! bash "$SCRIPT_DIR/packs/$p/install-pack.sh"; then
        fail "pack '$p' failed; stopping (packs after it were not run)"
        exit 1
    fi
done

ok "all selected packs completed:$(printf ' %s' "${SELECTED[@]}")"