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

BASE_URL="${BASE_URL:-http://43.167.242.65/xui-migrate-20260427-021339-2513}"
IMAGE="${IMAGE:-alireza7/x-ui:latest}"
CONTAINER_NAME="${CONTAINER_NAME:-x-ui}"
DB_DIR="${DB_DIR:-/root/x-ui/db}"
IMPORT_DIR="${IMPORT_DIR:-/root/x-ui-import}"
RESTART_POLICY="${RESTART_POLICY:-unless-stopped}"
TZ_VALUE="${TZ_VALUE:-Asia/Tehran}"

log() {
  printf '[restore-xui] %s\n' "$*"
}

require_root() {
  if [ "$(id -u)" -ne 0 ]; then
    echo "Please run as root." >&2
    exit 1
  fi
}

detect_platform() {
  case "$(uname -m)" in
    x86_64|amd64)
      PLATFORM="linux/amd64"
      ;;
    aarch64|arm64)
      PLATFORM="linux/arm64"
      ;;
    *)
      echo "Unsupported architecture: $(uname -m)" >&2
      exit 1
      ;;
  esac
}

install_docker() {
  if command -v docker >/dev/null 2>&1; then
    return
  fi

  log "Installing Docker"
  if command -v apt-get >/dev/null 2>&1; then
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io curl ca-certificates
  elif command -v dnf >/dev/null 2>&1; then
    dnf install -y docker curl ca-certificates
  elif command -v yum >/dev/null 2>&1; then
    yum install -y docker curl ca-certificates
  else
    echo "Unsupported package manager. Install Docker and curl manually." >&2
    exit 1
  fi

  if command -v systemctl >/dev/null 2>&1; then
    systemctl enable --now docker
  else
    service docker start
  fi
}

ensure_curl() {
  if command -v curl >/dev/null 2>&1; then
    return
  fi

  if command -v apt-get >/dev/null 2>&1; then
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y curl ca-certificates
  elif command -v dnf >/dev/null 2>&1; then
    dnf install -y curl ca-certificates
  elif command -v yum >/dev/null 2>&1; then
    yum install -y curl ca-certificates
  else
    echo "curl is required." >&2
    exit 1
  fi
}

download_files() {
  mkdir -p "$DB_DIR" "$IMPORT_DIR"

  log "Downloading x-ui.db"
  curl -fsSL --retry 3 --connect-timeout 10 \
    "$BASE_URL/x-ui.db" -o "$DB_DIR/x-ui.db"

  log "Downloading config.json"
  curl -fsSL --retry 3 --connect-timeout 10 \
    "$BASE_URL/config.json" -o "$IMPORT_DIR/config.json"

  if curl -fsSL --connect-timeout 10 "$BASE_URL/SHA256SUMS" -o "$IMPORT_DIR/SHA256SUMS"; then
    local db_sum config_sum
    db_sum="$(awk '/x-ui\.db$/{print $1}' "$IMPORT_DIR/SHA256SUMS" | head -n1)"
    config_sum="$(awk '/config\.json$/{print $1}' "$IMPORT_DIR/SHA256SUMS" | head -n1)"

    if [ -n "$db_sum" ]; then
      printf '%s  %s\n' "$db_sum" "$DB_DIR/x-ui.db" | sha256sum -c -
    fi
    if [ -n "$config_sum" ]; then
      printf '%s  %s\n' "$config_sum" "$IMPORT_DIR/config.json" | sha256sum -c -
    fi
  fi
}

restore_container() {
  log "Pulling image for $PLATFORM"
  docker pull --platform "$PLATFORM" "$IMAGE"

  if docker ps -a --format '{{.Names}}' | grep -Fxq "$CONTAINER_NAME"; then
    log "Removing existing container $CONTAINER_NAME"
    docker rm -f "$CONTAINER_NAME" >/dev/null
  fi

  log "Creating container $CONTAINER_NAME"
  docker create \
    --platform "$PLATFORM" \
    --name "$CONTAINER_NAME" \
    --restart "$RESTART_POLICY" \
    --network host \
    -e TZ="$TZ_VALUE" \
    -v "$DB_DIR:/etc/x-ui" \
    "$IMAGE" ./x-ui >/dev/null

  log "Injecting config.json"
  docker cp "$IMPORT_DIR/config.json" "$CONTAINER_NAME:/app/bin/config.json"

  log "Starting container"
  docker start "$CONTAINER_NAME" >/dev/null
}

show_status() {
  log "Container status"
  docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}' | sed -n '1,2p'
  log "Listening ports"
  ss -lntp 2>/dev/null | grep -E ':(7070|17198|38495|45142|50001|50002|50828)\b' || true
  log "Recent logs"
  docker logs --tail 20 "$CONTAINER_NAME" || true
}

main() {
  require_root
  detect_platform
  ensure_curl
  install_docker
  download_files
  restore_container
  show_status
}

main "$@"
