#!/usr/bin/env bash
set -euo pipefail

APP_NAME="loadsage"
APP_DIR="/opt/loadsage"
BIN_DIR="${APP_DIR}/bin"
PLUGIN_DIR="${APP_DIR}/plugins"
BIN_PATH="${BIN_DIR}/loadsage"
LOG_FILE="${APP_DIR}/install.log"
SOFTLIB_URL="softlib.service.ucloud.cn"
SOFTLIB_URL_PATH="usa/stress_test/loadsage"
BACKUP_URL="172.21.37.252"
PLUGIN_BACKUP_URL="http://${BACKUP_URL}/${SOFTLIB_URL_PATH}"

if ping -c 1 ${SOFTLIB_URL} > /dev/null 2>&1; then
  DOWNLOAD_URL="http://${SOFTLIB_URL}/${SOFTLIB_URL_PATH}/loadsage"
  PLUGIN_BASE_URL="http://${SOFTLIB_URL}/${SOFTLIB_URL_PATH}"
else
  DOWNLOAD_URL="http://${BACKUP_URL}/${SOFTLIB_URL_PATH}/loadsage"
  PLUGIN_BASE_URL="http://${BACKUP_URL}/${SOFTLIB_URL_PATH}"
fi

SERVICE_NAME="loadsage.service"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}"

LISTEN_ADDR=":18081"
AUTH_TOKEN="loadSaGe"

USER_NAME="root"
GROUP_NAME="root"

mkdir -p "${APP_DIR}"
touch "${LOG_FILE}"
chmod 644 "${LOG_FILE}"

exec > >(tee -a "${LOG_FILE}") 2>&1

log() {
  echo "[INFO] $(date '+%F %T') $*"
}

err() {
  echo "[ERROR] $(date '+%F %T') $*" >&2
}

check_root() {
  if [[ "${EUID}" -ne 0 ]]; then
    err "请使用 root 用户执行该脚本"
    exit 1
  fi
}

prepare_dirs() {
  log "创建目录..."
  mkdir -p "${BIN_DIR}"
  mkdir -p "${PLUGIN_DIR}"
}

check_dependency() {
  if ! command -v wget >/dev/null 2>&1; then
    log "wget 未安装，开始安装..."
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y wget
  fi
}

download_binary() {
  log "下载二进制文件: ${DOWNLOAD_URL}"
  wget -O "${BIN_PATH}" "${DOWNLOAD_URL}"
  chmod +x "${BIN_PATH}"
  log "二进制下载完成: ${BIN_PATH}"
}

write_service() {
  log "生成 systemd 服务文件: ${SERVICE_FILE}"
  cat > "${SERVICE_FILE}" <<EOF
[Unit]
Description=Loadsage Service
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${USER_NAME}
Group=${GROUP_NAME}
WorkingDirectory=${APP_DIR}
ExecStart=${BIN_PATH} --listen-addr ${LISTEN_ADDR} --auth-token ${AUTH_TOKEN} --plugin-base-url ${PLUGIN_BASE_URL} ${PLUGIN_BACKUP_URL:+--plugin-backup-url ${PLUGIN_BACKUP_URL} }--plugin-dir ./plugins
Restart=always
RestartSec=5
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF
}

reload_and_start() {
  log "重新加载 systemd 配置..."
  systemctl daemon-reload

  log "设置服务开机自启..."
  systemctl enable "${SERVICE_NAME}"

  log "启动/重启服务..."
  systemctl restart "${SERVICE_NAME}"

  log "查询服务状态..."
  systemctl --no-pager --full status "${SERVICE_NAME}" || true
}

show_summary() {
  log "安装完成"
  log "日志文件: ${LOG_FILE}"
  log "服务名称: ${SERVICE_NAME}"
  log "工作目录: ${APP_DIR}"
  log "启动命令:"
  echo "  ${BIN_PATH} --listen-addr ${LISTEN_ADDR} --auth-token ${AUTH_TOKEN} --plugin-base-url ${PLUGIN_BASE_URL} ${PLUGIN_BACKUP_URL:+--plugin-backup-url ${PLUGIN_BACKUP_URL} }--plugin-dir ./plugins"
}

main() {
  check_root
  check_dependency
  prepare_dirs
  download_binary
  write_service
  reload_and_start
  show_summary
}

main "$@"
