#!/usr/bin/env bash
# Quick bootstrap installer for target machines
# Usage: curl -fsSL https://devops.jasm.top/install.sh | bash

set -euo pipefail

echo "==> DevOps Environment Bootstrap"

INSTALL_DIR="/opt/devops_pub"
REPO_URL="https://github.com/lrobot/devops_pub.git"

if ! command -v git >/dev/null 2>&1; then
  echo "==> Installing git..."
  if command -v apt-get >/dev/null 2>&1; then
    apt-get update && apt-get install -y git
  elif command -v apk >/dev/null 2>&1; then
    apk add --no-cache git
  fi
fi

if [[ -d "$INSTALL_DIR" ]]; then
  echo "==> Updating ${INSTALL_DIR}..."
  git -C "$INSTALL_DIR" pull --ff-only || true
else
  echo "==> Cloning devops_pub into ${INSTALL_DIR}..."
  mkdir -p "$(dirname "$INSTALL_DIR")"
  git clone "$REPO_URL" "$INSTALL_DIR"
fi

if [[ -f "${INSTALL_DIR}/bin/devops" ]]; then
  ln -sfn "${INSTALL_DIR}/bin/devops" /usr/local/bin/devops
  chmod +x "${INSTALL_DIR}/bin/devops"
  echo "==> Installed 'devops' CLI to /usr/local/bin/devops."
  echo "==> Run 'devops status' or 'devops restore' to manage services."
fi
