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

INSTALL_DIR=/opt/next-terminal
BASE_URL=https://f.next-terminal.com/next-terminal
LANGUAGE=zh

msg() {
  if [[ "$LANGUAGE" == zh ]]; then printf '%s\n' "$1"; else printf '%s\n' "$2"; fi
}
ask() {
  printf '%s [%s]: ' "$1" "$2" >&3
  IFS= read -r ANSWER <&3
  ANSWER=${ANSWER:-$2}
}

# Read prompts from the terminal even when invoked with curl ... | bash.
if ! { exec 3<>/dev/tty; } 2>/dev/null; then
  printf '%s\n' '需要交互式终端 / An interactive terminal is required.' >&2
  exit 1
fi
printf '%s\n' '1) 中文' '2) English' >&3
while true; do
  ask '请选择语言 / Select language' 1
  case "$ANSWER" in
    1) LANGUAGE=zh; DEFAULT_SOURCE=1; break ;;
    2) LANGUAGE=en; DEFAULT_SOURCE=2; break ;;
  esac
  printf '%s\n' '请输入 1 或 2 / Enter 1 or 2.' >&3
done

for file in docker-compose.yaml docker-compose.yml compose.yaml compose.yml config.yaml data logs .env; do
  if [[ -e "$INSTALL_DIR/$file" || -L "$INSTALL_DIR/$file" ]]; then
    msg "${INSTALL_DIR} 中已存在 ${file}，安装已停止，避免覆盖现有部署。" "${INSTALL_DIR} already contains ${file}. Installation stopped to preserve the existing deployment." >&2
    exit 1
  fi
done

msg '请选择镜像源：1) 阿里云（中国大陆） 2) Docker Hub' 'Select image registry: 1) Alibaba Cloud (mainland China) 2) Docker Hub' >&3
while true; do
  ask "$(msg '镜像源' 'Image registry')" "$DEFAULT_SOURCE"
  case "$ANSWER" in
    1) TEMPLATE=docker-compose-aliyun.yaml; break ;;
    2) TEMPLATE=docker-compose.yaml; break ;;
  esac
  msg '请输入 1 或 2。' 'Enter 1 or 2.' >&3
done

if ! command -v docker >/dev/null 2>&1; then
  ask "$(msg '未安装 Docker，是否现在安装？输入 y 确认' 'Docker is not installed. Install it now? Enter y to confirm')" N
  case "$ANSWER" in
    y|Y) ;;
    *) msg '已取消，请安装 Docker 后重试。' 'Cancelled. Install Docker and try again.'; exit 0 ;;
  esac
  if [[ "$EUID" -ne 0 ]]; then
    msg '安装 Docker 需要 root 权限，请使用 sudo 重新运行。' 'Installing Docker requires root. Run the installer again with sudo.' >&2
    exit 1
  fi
  if [[ "$TEMPLATE" == docker-compose-aliyun.yaml ]]; then
    bash <(curl -s https://f.next-terminal.com/get-docker.sh) --mirror Aliyun
  else
    curl -fLsS https://get.docker.com/ | sh
  fi
fi
if ! docker compose version >/dev/null 2>&1 || ! docker info >/dev/null 2>&1; then
  msg 'Docker 或 Compose 不可用，请确认已安装 Compose 插件、Docker 已启动且当前用户有访问权限。' 'Docker or Compose is unavailable. Ensure the Compose plugin is installed, Docker is running, and your user has access.' >&2
  exit 1
fi

mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"
# Download both files before putting them in the installation directory.
TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT
msg '正在下载配置并启动服务…' 'Downloading configuration and starting services…'
curl -fsSL "$BASE_URL/$TEMPLATE" -o "$TMP_DIR/docker-compose.yaml"
curl -fsSL "$BASE_URL/config.yaml" -o "$TMP_DIR/config.yaml"
[[ -s "$TMP_DIR/docker-compose.yaml" && -s "$TMP_DIR/config.yaml" ]]
curl -fsSL "$BASE_URL/crt.sh" -o "$TMP_DIR/crt.sh"
[[ -s "$TMP_DIR/crt.sh" ]]
bash -n "$TMP_DIR/crt.sh"
cp "$TMP_DIR/docker-compose.yaml" "$TMP_DIR/config.yaml" "$TMP_DIR/crt.sh" .
chmod 755 crt.sh
docker compose up -d
msg '启动命令已完成，首次初始化可能需要一些时间。' 'Containers have been started. First-time initialization may take a while.'
msg '请将 <服务器IP> 替换为实际地址：' 'Replace <server-ip> with your server address:'
printf '%s\n' '  http://<server-ip>:8088/setup' '  http://<server-ip>:8088/login'
msg '安装目录：/opt/next-terminal' 'Installation directory: /opt/next-terminal'
msg '管理服务：' 'Manage services:'
printf '%s\n' '  sudo /opt/next-terminal/crt.sh stop' '  sudo /opt/next-terminal/crt.sh start' '  sudo /opt/next-terminal/crt.sh upgrade'
