#!/usr/bin/env bash
# MediaDNA Library — Team Workstation One-Key Docker Setup
# Official source: https://photonseed.com/guides/team-workstation-nas/
#
# Prepares persistent directories (UID/GID 10001, mode 0700), writes .env,
# downloads the official compose.yml if not already present, validates and
# starts the container, then prints your HTTPS setup URL, certificate
# fingerprint, and one-time bootstrap token.
#
# Safe by design:
# - Never modifies, moves, or uploads original video files (mounted read-only).
# - Refuses to place data/secrets directories inside the media folder.
# - Supports --dry-run to preview every step without making changes.

set -euo pipefail
export PATH="$PATH:/usr/local/bin:/usr/local/sbin"

COMPOSE_URL="https://photonseed.com/assets/guides/mediadna-workstation/compose.yml"
IMAGE_NAME="smallfrogs/mediadna-workstation"
WORKSTATION_UID=10001
WORKSTATION_GID=10001

INSTALL_DIR=""
MEDIA_DIR=""
BIND_IP=""
EXTRA_TLS_NAMES=""
PORT="18751"
CPUS=""
MEMORY=""
DRY_RUN=0
INFO_ONLY=0
ASSUME_YES=0

usage() {
  cat <<'EOF'
MediaDNA Library — Team Workstation One-Key Setup

Usage:
  bash setup-workstation.sh [options]

Options:
  --media <path>          Absolute path to your existing video folder (mounted read-only)
  --ip <ipv4>             Private LAN / VPN / Tailscale IPv4 address of this host
  --dir <path>            Directory for compose.yml, .env, data/ and secrets/
  --port <port>           Host HTTPS port (default: 18751)
  --extra-tls <names>     Optional comma-separated extra hostnames/IPs (e.g. nas.local,100.64.0.5)
  --cpus <n>              Optional CPU limit (default in compose.yml: 2)
  --memory <size>         Optional memory limit (default in compose.yml: 2g)
  --info                  Print HTTPS URL, TLS fingerprint and bootstrap token for an existing install
  --dry-run               Validate inputs and print planned configuration without changing files
  -y, --yes               Skip interactive confirmation prompt (requires --media and --ip)
  -h, --help              Show this help message

Examples:
  # Interactive (recommended — asks only for video folder and confirms auto-detected IP):
  bash setup-workstation.sh

  # Non-interactive:
  bash setup-workstation.sh --media /volume1/video --ip 192.168.1.20 -y

  # Show setup URL & one-time bootstrap token again:
  bash setup-workstation.sh --info --dir /volume1/docker/mediadna-workstation
EOF
}

die() {
  printf '\n[Error] %s\n' "$1" >&2
  exit 1
}

note() {
  printf '[MediaDNA] %s\n' "$1"
}

warn() {
  printf '[Warning] %s\n' "$1" >&2
}

is_ipv4() {
  local ip="$1"
  [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || return 1
  local IFS=.
  # shellcheck disable=SC2206
  local octets=($ip)
  local o
  for o in "${octets[@]}"; do
    (( 10#$o >= 0 && 10#$o <= 255 )) || return 1
  done
  return 0
}

is_port() {
  local p="$1"
  [[ "$p" =~ ^[0-9]+$ ]] && (( 10#$p >= 1 && 10#$p <= 65535 ))
}

normalize_path() {
  local raw="$1"
  # Strip trailing slashes except root "/"
  while [[ "$raw" != "/" && "$raw" == */ ]]; do
    raw="${raw%/}"
  done
  printf '%s' "$raw"
}

is_subpath() {
  local child="$1"
  local parent="$2"
  [[ "$child" == "$parent" || "$child" == "$parent"/* ]]
}

detect_private_ip() {
  local ip=""
  if command -v ip >/dev/null 2>&1; then
    ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src") {print $(i+1); exit}}' || true)"
  fi
  if [[ -z "$ip" ]] && command -v hostname >/dev/null 2>&1; then
    ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
  fi
  if [[ -z "$ip" ]] && command -v ifconfig >/dev/null 2>&1; then
    ip="$(ifconfig 2>/dev/null | awk '/inet / && $2 !~ /^127\./ {gsub(/^addr:/,"",$2); print $2; exit}' || true)"
  fi
  if is_ipv4 "$ip"; then
    printf '%s' "$ip"
  fi
}

detect_default_dir() {
  if [[ -d /volume1/docker ]]; then
    printf '/volume1/docker/mediadna-workstation'
  elif [[ -d /share/Container ]]; then
    printf '/share/Container/mediadna-workstation'
  elif [[ -d /mnt/user/appdata ]]; then
    printf '/mnt/user/appdata/mediadna-workstation'
  else
    printf '%s/mediadna-workstation' "$(pwd)"
  fi
}

run_privileged() {
  if [[ "$(id -u)" -eq 0 ]]; then
    "$@"
  elif command -v sudo >/dev/null 2>&1; then
    sudo "$@"
  else
    "$@"
  fi
}

read_file_safe() {
  local target="$1"
  if [[ -r "$target" ]]; then
    cat "$target"
    return 0
  fi
  if [[ "$(id -u)" -ne 0 ]] && command -v sudo >/dev/null 2>&1; then
    if [[ -t 0 ]]; then
      sudo cat "$target" 2>/dev/null && return 0
    else
      sudo -n cat "$target" 2>/dev/null && return 0
    fi
  fi
  return 1
}

run_docker() {
  if docker info >/dev/null 2>&1; then
    docker "$@"
  elif [[ "$(id -u)" -ne 0 ]] && command -v sudo >/dev/null 2>&1; then
    sudo docker "$@"
  else
    docker "$@"
  fi
}

strip_quotes() {
  local v="$1"
  v="${v#\"}"
  v="${v%\"}"
  v="${v#\'}"
  v="${v%\'}"
  printf '%s' "$v"
}

print_bootstrap_info() {
  local dir="$1"
  local env_file="$dir/.env"
  local bind_ip="$2"
  local port="$3"
  local data_dir="$4"
  local secrets_dir="$5"

  if [[ -f "$env_file" ]]; then
    local val
    val="$(grep -E '^WORKSTATION_BIND=' "$env_file" | tail -n 1 | cut -d= -f2- || true)"
    val="$(strip_quotes "$val")"
    [[ -n "$val" ]] && bind_ip="$val"
    val="$(grep -E '^WORKSTATION_PORT=' "$env_file" | tail -n 1 | cut -d= -f2- || true)"
    val="$(strip_quotes "$val")"
    [[ -n "$val" ]] && port="$val"
    val="$(grep -E '^WORKSTATION_DATA=' "$env_file" | tail -n 1 | cut -d= -f2- || true)"
    val="$(strip_quotes "$val")"
    [[ -n "$val" ]] && data_dir="$val"
    val="$(grep -E '^WORKSTATION_SECRETS=' "$env_file" | tail -n 1 | cut -d= -f2- || true)"
    val="$(strip_quotes "$val")"
    [[ -n "$val" ]] && secrets_dir="$val"
  fi

  local active_json="$data_dir/active.json"
  local active_content=""
  local gen=""
  local token=""
  local fp=""

  if active_content="$(read_file_safe "$active_json")"; then
    gen="$(printf '%s\n' "$active_content" | sed -n 's/.*"generation"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1 || true)"
  fi

  if [[ -n "$gen" ]]; then
    local token_file="$secrets_dir/generations/$gen/bootstrap.token"
    local cert_file="$secrets_dir/generations/$gen/tls.crt"
    token="$(read_file_safe "$token_file" | tr -d '\r\n' || true)"
    if command -v openssl >/dev/null 2>&1; then
      local cert_content=""
      if cert_content="$(read_file_safe "$cert_file")"; then
        fp="$(printf '%s\n' "$cert_content" | openssl x509 -noout -fingerprint -sha256 2>/dev/null | sed 's/^[^=]*=//' || true)"
      fi
    fi
  fi

  printf '\n============================================================\n'
  printf '  MediaDNA Library — Team Workstation Ready\n'
  printf '============================================================\n'
  printf '  Admin URL:         https://%s:%s\n' "${bind_ip:-<host-ip>}" "${port:-18751}"
  printf '  Scan source path:  /media/library  (read-only)\n'
  if [[ -n "$fp" ]]; then
    printf '  HTTPS SHA-256:     %s\n' "$fp"
  fi
  if [[ -n "$token" ]]; then
    printf '  Bootstrap token:   %s\n' "$token"
    printf '\n  Open the Admin URL above, verify the HTTPS certificate\n'
    printf '  fingerprint, and enter the one-time token to create your\n'
    printf '  administrator account (password >= 12 characters).\n'
  elif [[ -n "$gen" ]]; then
    printf '  Bootstrap token:   (already consumed or not present — admin may already be initialized)\n'
  else
    printf '  Bootstrap token:   (waiting for first generation — re-run with --info in a few seconds)\n'
  fi
  printf '============================================================\n\n'
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --media) MEDIA_DIR="${2:-}"; shift 2 ;;
    --ip) BIND_IP="${2:-}"; shift 2 ;;
    --dir) INSTALL_DIR="${2:-}"; shift 2 ;;
    --port) PORT="${2:-}"; shift 2 ;;
    --extra-tls) EXTRA_TLS_NAMES="${2:-}"; shift 2 ;;
    --cpus) CPUS="${2:-}"; shift 2 ;;
    --memory) MEMORY="${2:-}"; shift 2 ;;
    --info) INFO_ONLY=1; shift ;;
    --dry-run) DRY_RUN=1; shift ;;
    -y|--yes) ASSUME_YES=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) die "Unknown option: $1 (run with --help for usage)" ;;
  esac
done

if [[ "$INFO_ONLY" -eq 1 ]]; then
  INSTALL_DIR="${INSTALL_DIR:-$(detect_default_dir)}"
  INSTALL_DIR="$(normalize_path "$INSTALL_DIR")"
  [[ -f "$INSTALL_DIR/.env" ]] || die "No .env found in $INSTALL_DIR. Pass --dir <install-dir>."
  print_bootstrap_info "$INSTALL_DIR" "" "18751" "$INSTALL_DIR/data" "$INSTALL_DIR/secrets"
  exit 0
fi

# Interactive prompts when values were not supplied via flags
if [[ -z "$MEDIA_DIR" ]]; then
  [[ "$ASSUME_YES" -eq 0 && -t 0 ]] || die "--media <path> is required in non-interactive mode."
  printf 'Enter the absolute path to your video folder (e.g. /volume1/video): '
  read -r MEDIA_DIR
fi

if [[ -z "$BIND_IP" ]]; then
  local_default_ip="$(detect_private_ip || true)"
  if [[ "$ASSUME_YES" -eq 0 && -t 0 ]]; then
    if [[ -n "$local_default_ip" ]]; then
      printf 'Host private IPv4 address [%s]: ' "$local_default_ip"
    else
      printf 'Host private IPv4 address (e.g. 192.168.1.20): '
    fi
    read -r BIND_IP
    BIND_IP="${BIND_IP:-$local_default_ip}"
  else
    BIND_IP="$local_default_ip"
  fi
fi

if [[ -z "$INSTALL_DIR" ]]; then
  default_install_dir="$(detect_default_dir)"
  if [[ "$ASSUME_YES" -eq 0 && -t 0 ]]; then
    printf 'Workstation install directory [%s]: ' "$default_install_dir"
    read -r INSTALL_DIR
    INSTALL_DIR="${INSTALL_DIR:-$default_install_dir}"
  else
    INSTALL_DIR="$default_install_dir"
  fi
fi

MEDIA_DIR="$(normalize_path "$MEDIA_DIR")"
INSTALL_DIR="$(normalize_path "$INSTALL_DIR")"
DATA_DIR="$INSTALL_DIR/data"
SECRETS_DIR="$INSTALL_DIR/secrets"

# Validation
[[ "$MEDIA_DIR" == /* ]] || die "Video folder must be an absolute path: $MEDIA_DIR"
[[ "$INSTALL_DIR" == /* ]] || die "Install directory must be an absolute path: $INSTALL_DIR"
[[ "$DRY_RUN" -eq 1 || -d "$MEDIA_DIR" ]] || die "Video folder does not exist: $MEDIA_DIR"
is_ipv4 "$BIND_IP" || die "Invalid IPv4 address: ${BIND_IP:-<empty>}"
[[ "$BIND_IP" != "0.0.0.0" ]] || die "Use a specific private LAN/VPN IPv4 address, not 0.0.0.0."
is_port "$PORT" || die "Invalid port: $PORT"

if is_subpath "$DATA_DIR" "$MEDIA_DIR" || is_subpath "$SECRETS_DIR" "$MEDIA_DIR" || is_subpath "$MEDIA_DIR" "$DATA_DIR" || is_subpath "$MEDIA_DIR" "$SECRETS_DIR"; then
  die "Install directory ($INSTALL_DIR) must be outside your video folder ($MEDIA_DIR)."
fi

TLS_NAMES="localhost,127.0.0.1,$BIND_IP"
if [[ -n "$EXTRA_TLS_NAMES" ]]; then
  EXTRA_TLS_NAMES="$(printf '%s' "$EXTRA_TLS_NAMES" | tr -d '[:space:]' | sed 's/^,*//;s/,*$//')"
  if [[ -n "$EXTRA_TLS_NAMES" ]]; then
    TLS_NAMES="$TLS_NAMES,$EXTRA_TLS_NAMES"
  fi
fi

if [[ "$DRY_RUN" -eq 1 ]]; then
  cat <<EOF
[Dry run] No files or containers were modified.
  INSTALL_DIR=$INSTALL_DIR
  WORKSTATION_DATA=$DATA_DIR
  WORKSTATION_SECRETS=$SECRETS_DIR
  WORKSTATION_MEDIA=$MEDIA_DIR
  WORKSTATION_BIND=$BIND_IP
  WORKSTATION_TLS_NAMES=$TLS_NAMES
  WORKSTATION_PORT=$PORT
EOF
  exit 0
fi

# Check Docker & Docker Compose v2
command -v docker >/dev/null 2>&1 || die "Docker is not installed or not in PATH."
run_docker compose version >/dev/null 2>&1 || die "Docker Compose v2 ('docker compose') is required."

if [[ "$ASSUME_YES" -eq 0 && -t 0 ]]; then
  printf '\nPlanned Team Workstation setup:\n'
  printf '  Install directory:  %s\n' "$INSTALL_DIR"
  printf '  Video folder (RO):  %s -> /media/library\n' "$MEDIA_DIR"
  printf '  Private HTTPS:      https://%s:%s\n' "$BIND_IP" "$PORT"
  printf '  TLS names:          %s\n\n' "$TLS_NAMES"
  printf 'Continue? [Y/n]: '
  read -r confirm
  if [[ -n "$confirm" && ! "$confirm" =~ ^[Yy]$ ]]; then
    note "Cancelled."
    exit 0
  fi
fi

note "Preparing directories in $INSTALL_DIR..."
if ! mkdir -p "$INSTALL_DIR" 2>/dev/null; then
  run_privileged mkdir -p "$INSTALL_DIR"
  run_privileged chown "$(id -u):$(id -g)" "$INSTALL_DIR"
fi
run_privileged mkdir -p "$DATA_DIR" "$SECRETS_DIR"
run_privileged chown "$WORKSTATION_UID:$WORKSTATION_GID" "$DATA_DIR" "$SECRETS_DIR"
run_privileged chmod 0700 "$DATA_DIR" "$SECRETS_DIR"

# Fetch official compose.yml if not already present in INSTALL_DIR
COMPOSE_FILE="$INSTALL_DIR/compose.yml"
if [[ ! -f "$COMPOSE_FILE" ]]; then
  if [[ -f "$(dirname "$0")/compose.yml" ]]; then
    note "Copying local compose.yml to $COMPOSE_FILE..."
    cp "$(dirname "$0")/compose.yml" "$COMPOSE_FILE"
  elif command -v curl >/dev/null 2>&1; then
    note "Downloading official compose.yml..."
    curl -fsSL "$COMPOSE_URL" -o "$COMPOSE_FILE"
  elif command -v wget >/dev/null 2>&1; then
    note "Downloading official compose.yml..."
    wget -qO "$COMPOSE_FILE" "$COMPOSE_URL"
  else
    die "Neither curl nor wget is available to download compose.yml."
  fi
fi

ENV_FILE="$INSTALL_DIR/.env"
note "Writing $ENV_FILE..."
{
  printf '# Generated by MediaDNA Library Team Workstation one-key setup\n'
  printf 'WORKSTATION_DATA=%s\n' "$DATA_DIR"
  printf 'WORKSTATION_SECRETS=%s\n' "$SECRETS_DIR"
  printf 'WORKSTATION_MEDIA=%s\n' "$MEDIA_DIR"
  printf 'WORKSTATION_BIND=%s\n' "$BIND_IP"
  printf 'WORKSTATION_TLS_NAMES=%s\n' "$TLS_NAMES"
  printf 'WORKSTATION_PORT=%s\n' "$PORT"
  [[ -n "$CPUS" ]] && printf 'WORKSTATION_CPUS=%s\n' "$CPUS"
  [[ -n "$MEMORY" ]] && printf 'WORKSTATION_MEMORY=%s\n' "$MEMORY"
} > "$ENV_FILE"
chmod 0600 "$ENV_FILE"

# Advisory read check for UID 10001 on the media folder (non-destructive)
if [[ ! -r "$MEDIA_DIR" ]] || [[ "$(stat -c '%a' "$MEDIA_DIR" 2>/dev/null || stat -f '%Lp' "$MEDIA_DIR" 2>/dev/null || echo '755')" == *0 ]]; then
  warn "Make sure UID/GID $WORKSTATION_UID has read/traverse access to $MEDIA_DIR (never moves or modifies originals)."
fi

note "Validating Docker Compose configuration..."
(cd "$INSTALL_DIR" && run_docker compose config --quiet)

note "Pulling $IMAGE_NAME from Docker Hub..."
run_docker pull "$IMAGE_NAME"

note "Starting MediaDNA Team Workstation..."
(cd "$INSTALL_DIR" && run_docker compose up -d --wait --no-build)

print_bootstrap_info "$INSTALL_DIR" "$BIND_IP" "$PORT" "$DATA_DIR" "$SECRETS_DIR"
