#!/usr/bin/env bash
# Web Backtester 실전 자동매매 — macOS / Linux 설치 부트스트랩
#
#   curl -fsSL https://sleepwelltrade.com/install.sh | bash
#   curl -fsSL https://sleepwelltrade.com/install.sh | bash -s -- --docker
#
# 패키지를 ~/backtester-live 에 내려받아 풀고 설정 마법사를 실행합니다.
# API 키는 이 컴퓨터를 떠나지 않습니다.
set -euo pipefail

BASE="${BACKTESTER_BASE:-https://sleepwelltrade.com}"
DIR="${BACKTESTER_HOME:-$HOME/backtester-live}"
DOCKER=0
for a in "$@"; do [[ "$a" == "--docker" ]] && DOCKER=1; done

echo "── Web Backtester 실전 자동매매 설치 ──"
echo "설치 위치: $DIR"

command -v curl >/dev/null || { echo "curl이 필요합니다" >&2; exit 1; }
command -v tar >/dev/null || { echo "tar가 필요합니다" >&2; exit 1; }

have_node() {
  command -v node >/dev/null 2>&1 || return 1
  local major
  major="$(node -v | sed 's/^v//' | cut -d. -f1)"
  [[ "$major" -ge 20 ]]
}

if [[ $DOCKER -eq 0 ]] && ! have_node; then
  if command -v docker >/dev/null 2>&1; then
    echo "Node.js 20+가 없지만 도커가 있습니다 → 도커 방식으로 진행합니다."
    DOCKER=1
  else
    echo ""
    echo "Node.js 20 이상이 필요합니다. 설치 후 다시 실행해 주세요:"
    echo "  macOS : brew install node   (또는 https://nodejs.org)"
    echo "  Ubuntu: sudo apt install -y nodejs npm   (버전이 낮으면 https://nodejs.org)"
    echo "또는 도커만으로 설치: 이 스크립트에 --docker 를 붙여 실행"
    exit 1
  fi
fi

mkdir -p "$DIR"
echo "패키지 다운로드 중..."
curl -fsSL "$BASE/dl/backtester-live.tar.gz" | tar xz -C "$DIR"
cd "$DIR"

# anonymous install ping (platform only, no PII) — opt out: BACKTESTER_NO_TELEMETRY=1
# label convention must match the runner's (lib/telemetry.mjs): process.platform
# with a "docker-" prefix, so installs and runs land in the same bucket
if [[ -z "${BACKTESTER_NO_TELEMETRY:-}" ]]; then
  OS="$(uname -s | tr 'A-Z' 'a-z')"
  DEPLOY="$([[ $DOCKER -eq 1 ]] && echo docker || echo native)"
  curl -fsS -m 5 -X POST "$BASE/api/track" -H 'Content-Type: application/json' \
    -d "{\"type\":\"pkg_install\",\"exchange\":\"$([[ $DOCKER -eq 1 ]] && echo "docker-$OS" || echo "$OS")\",\"platform\":\"$OS\",\"deploy_type\":\"$DEPLOY\"}" \
    >/dev/null 2>&1 || true
fi

# when run via `curl | bash` stdin is the script pipe (already at EOF) — the
# wizard must read the real terminal, or every prompt would auto-answer with
# its default. Fall back to plain stdin only when no tty exists (headless).
run_interactive() {
  if [[ -t 0 ]]; then
    "$@"
  elif { : < /dev/tty; } 2>/dev/null; then
    "$@" < /dev/tty
  else
    "$@"
  fi
}

if [[ $DOCKER -eq 1 ]]; then
  if ! command -v docker >/dev/null 2>&1; then
    echo ""
    echo "도커가 설치되어 있지 않습니다."
    if [[ -r /dev/tty ]] && [[ "$(uname -s)" == "Linux" ]]; then
      read -r -p "공식 스크립트(get.docker.com)로 지금 설치할까요? (sudo 필요) (y/n) [y] " ans < /dev/tty
      if [[ -z "$ans" || "$ans" =~ ^[Yy] ]]; then
        curl -fsSL https://get.docker.com | sudo sh
      fi
    fi
    command -v docker >/dev/null 2>&1 || {
      echo "직접 설치 후 다시 실행해 주세요: https://docs.docker.com/engine/install/" >&2
      exit 1
    }
  fi
  # root가 아니고 docker 그룹도 아니면 sudo로 실행
  DOCKER="docker"
  if ! docker info >/dev/null 2>&1; then
    if sudo docker info >/dev/null 2>&1; then
      DOCKER="sudo docker"
      echo "(docker 그룹 권한이 없어 sudo로 실행합니다 — 다음부터 sudo 없이 쓰려면:"
      echo "  sudo usermod -aG docker \$USER && newgrp docker)"
    else
      echo "docker 데몬에 접근할 수 없습니다. 데몬 상태를 확인해 주세요: sudo systemctl status docker" >&2
      exit 1
    fi
  fi
  echo ""
  echo "도커 설정 마법사를 시작합니다..."
  # The host wrapper consumes the wizard's restart/timing choice. A plain
  # `compose up -d` would leave an existing runner alive with its old config.
  run_interactive bash setup-docker.sh
else
  echo ""
  run_interactive node live/setup.mjs
fi
