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

ROOT=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
# Release scripts live beside nowdns; source scripts live under scripts/.
if [[ ! -f $ROOT/nowdns && -d $ROOT/../bin ]]; then
  ROOT=$(CDPATH= cd -- "$ROOT/.." && pwd)
fi
ACTION=menu
LANGUAGE=auto
EXECUTABLE=
CONFIG_PATH=
LISTEN_ADDRESS=
DATABASE_PATH=
COOKIE_SECURE=false

usage() {
  say '用法: ./service.sh [选项]' 'Usage: ./service.sh [options]'
  say '  --action ACTION       menu、install、uninstall、enable、disable、start、stop、restart、status、logs、config、help' '  --action ACTION       menu, install, uninstall, enable, disable, start, stop, restart, status, logs, config, help'
  say '  --language LANGUAGE   auto、zh、en' '  --language LANGUAGE   auto, zh, en'
  say '  --executable PATH     NowDNS 可执行文件路径' '  --executable PATH     NowDNS executable path'
  say '  --config PATH         安装时保存的配置路径' '  --config PATH         Config path stored during installation'
  say '  --listen ADDRESS      安装时保存的监听地址' '  --listen ADDRESS      Listen address stored during installation'
  say '  --database PATH       安装时保存的数据库路径' '  --database PATH       Database path stored during installation'
  say '  --cookie-secure       安装时启用 Secure Cookie' '  --cookie-secure       Enable Secure cookies in stored service options'
}

while (($#)); do
  case "$1" in
    --action) ACTION=$2; shift 2 ;;
    --language) LANGUAGE=$2; shift 2 ;;
    --executable) EXECUTABLE=$2; shift 2 ;;
    --config) CONFIG_PATH=$2; shift 2 ;;
    --listen) LISTEN_ADDRESS=$2; shift 2 ;;
    --database) DATABASE_PATH=$2; shift 2 ;;
    --cookie-secure) COOKIE_SECURE=true; shift ;;
    --help|-h) ACTION=help; shift ;;
    *) echo "Unknown option: $1" >&2; exit 2 ;;
  esac
done

case "$LANGUAGE" in
  auto) [[ ${LANG:-} == zh_* || ${LC_ALL:-} == zh_* ]] && LANGUAGE=zh || LANGUAGE=en ;;
  zh|en) ;;
  *) echo "--language must be auto, zh, or en" >&2; exit 2 ;;
esac

t() { [[ $LANGUAGE == zh ]] && printf '%s' "$1" || printf '%s' "$2"; }
say() { printf '%s\n' "$(t "$1" "$2")"; }

resolve_executable() {
  if [[ -n $EXECUTABLE ]]; then
    [[ $EXECUTABLE = /* ]] || EXECUTABLE="$ROOT/$EXECUTABLE"
    [[ -f $EXECUTABLE ]] || { say "找不到 NowDNS 可执行文件: $EXECUTABLE" "NowDNS executable was not found: $EXECUTABLE" >&2; exit 1; }
    printf '%s\n' "$EXECUTABLE"
    return
  fi
  local os arch candidate
  os=$(uname -s)
  [[ $os == Linux ]] || { say '此脚本仅支持 Linux。' 'This script supports Linux only.' >&2; exit 1; }
  case "$(uname -m)" in
    x86_64|amd64) arch=amd64 ;;
    arm64|aarch64) arch=arm64 ;;
    *) say "不支持的 CPU 架构: $(uname -m)" "Unsupported CPU architecture: $(uname -m)" >&2; exit 1 ;;
  esac
  if [[ -f $ROOT/nowdns ]]; then
    chmod +x "$ROOT/nowdns"
    printf '%s\n' "$ROOT/nowdns"
    return
  fi
  candidate=$(find "$ROOT/bin" -maxdepth 1 -type f -name "nowdns-*-linux-$arch" -print 2>/dev/null | sort | tail -n 1 || true)
  [[ -n $candidate ]] || { say "未找到 nowdns 或 bin/nowdns-*-linux-$arch。请先下载或构建 Linux 版本。" "No nowdns or bin/nowdns-*-linux-$arch was found. Download or build the Linux release first." >&2; exit 1; }
  chmod +x "$candidate"
  printf '%s\n' "$candidate"
}

require_root() {
  [[ $EUID -eq 0 ]] || { say '请使用 sudo 运行此操作。' 'Run this operation with sudo.' >&2; exit 1; }
}

invoke_service() {
  local verb=$1 binary
  binary=$(resolve_executable)
  local args=(service "$verb")
  if [[ $verb == install ]]; then
    [[ -n $CONFIG_PATH ]] && args+=(--config "$CONFIG_PATH")
    [[ -n $LISTEN_ADDRESS ]] && args+=(--listen "$LISTEN_ADDRESS")
    [[ -n $DATABASE_PATH ]] && args+=(--database "$DATABASE_PATH")
    [[ $COOKIE_SECURE == true ]] && args+=(--cookie-secure=true)
  fi
  (cd "$ROOT" && "$binary" "${args[@]}")
}

show_logs() {
  local app="$ROOT/data/logs/nowdns.log" access="$ROOT/data/logs/nowdns-access.log"
  say "应用日志: $app" "Application log: $app"
  [[ -f $app ]] && tail -n 50 "$app" || say '应用日志尚未创建。' 'Application log has not been created yet.'
  printf '\n'
  say "HTTP 访问日志: $access" "HTTP access log: $access"
  [[ -f $access ]] && tail -n 50 "$access" || say 'HTTP 访问日志尚未创建。' 'HTTP access log has not been created yet.'
}

show_config() {
  local config="$ROOT/config.yaml"
  [[ -f $config ]] && cat "$config" || say '尚未生成 config.yaml。执行安装会生成默认配置。' 'config.yaml has not been generated. Installing the service creates the default configuration.'
}

run_action() {
  case "$1" in
    install|uninstall|enable|disable|start|stop|restart) require_root; invoke_service "$1" ;;
    status) invoke_service status ;;
    logs) show_logs ;;
    config) show_config ;;
    help) usage ;;
    *) say "未知操作: $1" "Unknown action: $1" >&2; exit 2 ;;
  esac
}

menu() {
  clear
  say 'NowDNS Linux 服务管理' 'NowDNS Linux Service Manager'
  say "工作目录: $ROOT" "Working directory: $ROOT"
  printf '\n'
  say '1. 安装并设置开机自启' '1. Install and enable automatic startup'
  say '2. 启动服务' '2. Start service'
  say '3. 停止服务' '3. Stop service'
  say '4. 重启服务' '4. Restart service'
  say '5. 查看服务状态' '5. Show service status'
  say '6. 查看最近日志' '6. Show recent logs'
  say '7. 查看配置' '7. Show configuration'
  say '8. 启用开机自启' '8. Enable automatic startup'
  say '9. 停止并禁用开机自启' '9. Stop and disable automatic startup'
  say '10. 卸载服务' '10. Uninstall service'
  say '11. 切换中文/English' '11. Switch Chinese/English'
  say '0. 退出' '0. Exit'
  read -r -p "$(t '请选择: ' 'Choose an action: ')" MENU_SELECTION
}

if [[ $ACTION != menu ]]; then
  run_action "$ACTION"
  exit 0
fi

while true; do
  menu
  selection=$MENU_SELECTION
  case "$selection" in
    1) run_action install ;;
    2) run_action start ;;
    3) run_action stop ;;
    4) run_action restart ;;
    5) run_action status ;;
    6) run_action logs ;;
    7) run_action config ;;
    8) run_action enable ;;
    9) run_action disable ;;
    10) run_action uninstall ;;
    11) [[ $LANGUAGE == zh ]] && LANGUAGE=en || LANGUAGE=zh; continue ;;
    0) exit 0 ;;
    *) say '无效选择。' 'Invalid selection.' ;;
  esac
  [[ $selection == 11 ]] || read -r -p "$(t '按 Enter 返回菜单' 'Press Enter to return to the menu')" _
done
