#!/bin/sh
set -e

AGENT_SHARE="/usr/share/ocsinventory-agent"
AGENT_BIN="/usr/local/bin/ocsinventory-cli"
SYMLINK="/usr/bin/ocsinventory-cli"
CONFIG_DIR="/etc/ocsinventory-agent"
CONFIG_FILE="${CONFIG_DIR}/config.json"
SERVICE_FILE="/etc/systemd/system/ocsinventory-agent.service"
LOG_FILE="/var/log/ocsinventory-agent/ocsinventory-agent.log"
DATA_DIR="/var/lib/ocsinventory-data"
LOG_DIR="$(dirname "$LOG_FILE")"

is_interactive_install() {
    [ -t 0 ] && [ -t 1 ] && [ "${DEBIAN_FRONTEND:-}" != "noninteractive" ]
}

is_fresh_install() {
    [ "$1" = "configure" ] && [ -z "$2" ]
}

if is_fresh_install "$1" "$2" && is_interactive_install && [ -x "${AGENT_SHARE}/install.sh" ]; then
    rm -rf "${CONFIG_DIR}"
    "${AGENT_SHARE}/install.sh"
    exit 0
fi

install -d /usr/local/bin
if [ -f "${AGENT_SHARE}/ocsinventory-cli" ]; then
    install -m 0755 "${AGENT_SHARE}/ocsinventory-cli" "${AGENT_BIN}"
fi

if [ ! -L "${SYMLINK}" ]; then
    ln -s "${AGENT_BIN}" "${SYMLINK}" || true
fi

install -d "${CONFIG_DIR}"
if [ ! -f "${CONFIG_FILE}" ]; then
    cat <<'CONFIG' > "${CONFIG_FILE}"
{
  "url": "",
  "username": "",
  "password": "",
  "mode": 4,
  "log_level": 3,
  "log_file": true,
  "log_file_path": "/var/log/ocsinventory-agent/ocsinventory-agent.log",
  "data_directory": "/var/lib/ocsinventory-data",
  "certificate": "none",
  "bypass_certificate": false
}
CONFIG
fi

install -d "${DATA_DIR}"
install -d "${LOG_DIR}"
touch "${LOG_FILE}"

if [ -f "${AGENT_SHARE}/ocsinventory-agent.service" ]; then
    install -m 0644 "${AGENT_SHARE}/ocsinventory-agent.service" "${SERVICE_FILE}"
fi

systemctl daemon-reload >/dev/null 2>&1 || true

echo "OCSInventory Agent installed in local mode (no template)."
echo "Run /usr/share/ocsinventory-agent/install.sh for interactive setup."
