#!/bin/bash
# ============================================================
# GUARDiA ITSM 서버 환경 구성
# Oracle Cloud Ubuntu 22.04 ARM (Ampere A1)
# 실행: bash 06_guardia_server_setup.sh
# ============================================================

set -e
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
info()    { echo -e "${GREEN}[OK]${NC} $1"; }
warn()    { echo -e "${YELLOW}[!]${NC} $1"; }
section() { echo -e "\n${CYAN}════════════════════════════════${NC}"; echo -e "${CYAN} $1${NC}"; echo -e "${CYAN}════════════════════════════════${NC}"; }

# ── 1. Python 3.11 ──────────────────────────────────────────
section "1. Python 3.11 설치"
sudo apt-get install -y python3.11 python3.11-venv python3.11-dev python3-pip
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1
python3 --version
info "Python 3.11 설치 완료"

# ── 2. PostgreSQL 15 ─────────────────────────────────────────
section "2. PostgreSQL 15 설치"
sudo apt-get install -y postgresql postgresql-contrib
sudo systemctl enable postgresql
sudo systemctl start postgresql

# DB / 사용자 생성
sudo -u postgres psql <<PSQL
CREATE USER guardia WITH PASSWORD 'G@urd1a_2026!';
CREATE DATABASE guardia_db OWNER guardia;
GRANT ALL PRIVILEGES ON DATABASE guardia_db TO guardia;
CREATE DATABASE zioinfo_db OWNER guardia;
PSQL
info "PostgreSQL 설치 및 DB 생성 완료"

# ── 3. Ollama + LLM ─────────────────────────────────────────
section "3. Ollama 설치 (온프레미스 AI 엔진)"
curl -fsSL https://ollama.ai/install.sh | sh
sudo systemctl enable ollama
sudo systemctl start ollama
sleep 3

# LLM 모델 다운로드 (ARM 최적화)
echo "Llama-3 8B 모델 다운로드 중 (약 4.7GB)..."
ollama pull llama3:8b
info "Ollama + Llama-3 8B 설치 완료"

# ── 4. GUARDiA 디렉터리 ──────────────────────────────────────
section "4. GUARDiA ITSM 디렉터리 구조 생성"
sudo mkdir -p /opt/guardia/{app,logs,backups,uploads,static}
sudo chown -R ubuntu:ubuntu /opt/guardia
info "GUARDiA 디렉터리 생성 완료"

# ── 5. Python 가상환경 ───────────────────────────────────────
section "5. Python 가상환경 및 패키지 설치"
python3 -m venv /opt/guardia/venv
source /opt/guardia/venv/bin/activate

pip install --upgrade pip
pip install \
  fastapi==0.115.0 \
  uvicorn[standard]==0.30.0 \
  sqlalchemy==2.0.35 \
  alembic==1.13.0 \
  asyncpg==0.29.0 \
  psycopg2-binary==2.9.9 \
  python-jose[cryptography]==3.3.0 \
  passlib[bcrypt]==1.7.4 \
  python-multipart==0.0.9 \
  httpx==0.27.0 \
  paramiko==3.4.0 \
  openpyxl==3.1.5 \
  reportlab==4.2.0 \
  python-dotenv==1.0.1 \
  pydantic-settings==2.4.0 \
  aiofiles==23.2.1 \
  pyotp==2.9.0 \
  cryptography==43.0.1 \
  websockets==12.0

deactivate
info "Python 패키지 설치 완료"

# ── 6. .env 파일 생성 ────────────────────────────────────────
section "6. 환경 변수 파일 생성"
cat > /opt/guardia/app/.env <<ENV
# GUARDiA ITSM 환경 설정
APP_ENV=production
SECRET_KEY=$(openssl rand -hex 32)
DATABASE_URL=postgresql+asyncpg://guardia:G@urd1a_2026!@localhost:5432/guardia_db
OLLAMA_BASE_URL=http://localhost:11434
LLM_MODEL=llama3:8b
ALLOWED_ORIGINS=["https://itsm.zioinfo.co.kr","http://localhost:3000"]

# 라이선스
LICENSE_KEY=
TRIAL_DURATION_DAYS=30

# 이메일 (선택)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=
SMTP_PASSWORD=
ENV
chmod 600 /opt/guardia/app/.env
info ".env 파일 생성 완료"

# ── 7. systemd 서비스 ────────────────────────────────────────
section "7. GUARDiA systemd 서비스 등록"
sudo tee /etc/systemd/system/guardia.service > /dev/null <<SERVICE
[Unit]
Description=GUARDiA ITSM Platform
After=network.target postgresql.service ollama.service

[Service]
User=ubuntu
WorkingDirectory=/opt/guardia/app
Environment="PATH=/opt/guardia/venv/bin"
ExecStart=/opt/guardia/venv/bin/uvicorn main:app --host 0.0.0.0 --port 8001 --workers 2
Restart=on-failure
RestartSec=10
StandardOutput=append:/opt/guardia/logs/guardia.log
StandardError=append:/opt/guardia/logs/error.log

[Install]
WantedBy=multi-user.target
SERVICE

sudo systemctl daemon-reload
sudo systemctl enable guardia
info "GUARDiA 서비스 등록 완료"

section "✅ GUARDiA 서버 환경 구성 완료!"
echo ""
echo "다음 단계: bash 07_nginx_all.sh 실행"
