#!/bin/bash
#
# SearXNG Setup Script
# Usage: curl -sL https://docs.techswan.online/scripts/searxng-setup.sh | sudo bash
#
set -euo pipefail

echo "=== SearXNG Setup ==="

# Docker確認
if ! command -v docker &> /dev/null; then
    echo "[INFO] Installing Docker..."
    apt-get update
    apt-get install -y docker.io
fi

# docker-compose確認
if ! docker compose version &> /dev/null 2>&1; then
    echo "[INFO] Installing docker-compose-plugin..."
    apt-get install -y docker-compose-plugin || apt-get install -y docker-compose
fi

apt-get install -y curl jq

# Dockerサービス有効化
systemctl enable docker
systemctl start docker

# SearXNG用ディレクトリ
mkdir -p /opt/searxng/searxng
cd /opt/searxng

# docker-compose.yml作成
cat > docker-compose.yml << 'EOF'
version: '3.8'

services:
  searxng:
    image: searxng/searxng:latest
    container_name: searxng
    restart: unless-stopped
    ports:
      - "8080:8080"
    volumes:
      - ./searxng:/etc/searxng:rw
    environment:
      - SEARXNG_BASE_URL=http://localhost:8080
    cap_drop:
      - ALL
    cap_add:
      - CHOWN
      - SETGID
      - SETUID
EOF

# settings.yml作成
cat > searxng/settings.yml << 'EOF'
use_default_settings: true

general:
  instance_name: "SearXNG Local"
  debug: false

search:
  safe_search: 0
  autocomplete: "duckduckgo"
  default_lang: "ja-JP"
  formats:
    - html
    - json

server:
  secret_key: "$(openssl rand -hex 32)"
  limiter: false
  image_proxy: true

ui:
  static_use_hash: true
  default_theme: simple
  default_locale: "ja"

engines:
  - name: google
    disabled: false
  - name: bing
    disabled: false
  - name: duckduckgo
    disabled: false
  - name: brave
    disabled: false
  - name: wikipedia
    disabled: false
  - name: github
    disabled: false

outgoing:
  request_timeout: 5.0
  max_request_timeout: 15.0
EOF

# secret_key生成
SECRET_KEY=$(openssl rand -hex 32)
sed -i "s/\$(openssl rand -hex 32)/$SECRET_KEY/" searxng/settings.yml

# 起動
if docker compose version &> /dev/null 2>&1; then
    docker compose up -d
else
    docker-compose up -d
fi

echo ""
echo "=== SearXNG Setup Complete ==="
echo ""
echo "Web UI:  http://localhost:8080"
echo "API:     http://localhost:8080/search?q=test&format=json"
echo ""
echo "Test:"
echo "  curl 'http://localhost:8080/search?q=hello&format=json' | jq '.results[:3]'"
echo ""
