#!/usr/bin/env bash
# Cài và cấu hình OCS Inventory Agent (Linux) trỏ về server phục vụ script này.
# Cách dùng:
#   curl -fsSL http://<IP>:8888/install-agent.sh | sudo bash
#   curl -fsSL http://<IP>:8888/install-agent.sh | sudo bash -s -- http://<IP>:8888/ocsinventory

set -euo pipefail

SERVER_URL="${1:-}"

if [[ -z "$SERVER_URL" ]]; then
  if [[ -n "${OCS_SERVER:-}" ]]; then
    SERVER_URL="$OCS_SERVER"
  elif [[ -n "${HTTP_REFERER:-}" ]]; then
    # Khi tải qua trình duyệt; thường không có khi pipe từ curl
    base="${HTTP_REFERER%/}"
    SERVER_URL="${base%/}/ocsinventory"
    SERVER_URL="${SERVER_URL//\/ocsinventory\/ocsinventory/\/ocsinventory}"
  fi
fi

# Suy ra URL server từ nơi tải script (curl -fsSL http://host:port/install-agent.sh)
if [[ -z "$SERVER_URL" ]] && [[ -n "${DOWNLOAD_BASE:-}" ]]; then
  SERVER_URL="${DOWNLOAD_BASE%/}/ocsinventory"
fi

detect_from_proc() {
  # Khi chạy: curl .../install-agent.sh | bash — bash đọc stdin, không biết URL.
  # Người dùng nên truyền URL hoặc đặt OCS_SERVER.
  return 1
}

if [[ -z "$SERVER_URL" ]]; then
  cat <<'EOF' >&2
Thiếu URL Communication Server.

Cách dùng:
  export OCS_SERVER=http://<IP>:8888/ocsinventory
  curl -fsSL http://<IP>:8888/install-agent.sh | sudo -E bash

Hoặc:
  curl -fsSL http://<IP>:8888/install-agent.sh | sudo bash -s -- http://<IP>:8888/ocsinventory
EOF
  exit 1
fi

# Chuẩn hóa: bỏ slash cuối, đảm bảo kết thúc bằng /ocsinventory
SERVER_URL="${SERVER_URL%/}"
if [[ "$SERVER_URL" != */ocsinventory ]]; then
  SERVER_URL="${SERVER_URL}/ocsinventory"
fi

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Cần chạy với quyền root (sudo)." >&2
  exit 1
fi

echo "==> OCS server: $SERVER_URL"

CFG_DIR="/etc/ocsinventory"
CFG_FILE="${CFG_DIR}/ocsinventory-agent.cfg"
LOG_FILE="/var/log/ocsinventory-agent.log"

install_debian() {
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -qq
  apt-get install -y -qq ocsinventory-agent
}

install_rhel() {
  if command -v dnf >/dev/null 2>&1; then
    dnf install -y ocsinventory-agent || dnf install -y ocsinventory-agent-core
  else
    yum install -y ocsinventory-agent || yum install -y ocsinventory-agent-core
  fi
}

if command -v ocsinventory-agent >/dev/null 2>&1; then
  echo "==> ocsinventory-agent đã có sẵn"
elif [[ -f /etc/debian_version ]]; then
  echo "==> Cài ocsinventory-agent (APT)..."
  install_debian
elif [[ -f /etc/redhat-release ]] || [[ -f /etc/centos-release ]]; then
  echo "==> Cài ocsinventory-agent (YUM/DNF)..."
  install_rhel
else
  echo "Chưa hỗ trợ distro này. Cài thủ công ocsinventory-agent rồi chạy lại script." >&2
  exit 1
fi

mkdir -p "$CFG_DIR"
umask 077
cat >"$CFG_FILE" <<EOF
server=${SERVER_URL}
logfile=${LOG_FILE}
debug=1
EOF
chmod 600 "$CFG_FILE"

echo "==> Đã ghi cấu hình: $CFG_FILE"
echo "==> Gửi inventory lần đầu..."
ocsinventory-agent --server="${SERVER_URL}" --debug || ocsinventory-agent --debug

echo
echo "Xong. Kiểm tra máy trên Web Console: ${SERVER_URL%/ocsinventory}/ocsreports/"
echo "Log: $LOG_FILE"
