#!/bin/bash
# postinst — chạy SAU khi unpack gói, với $1 = status (install/upgrade/replace).
# File nằm trong DEBIAN/ của cây package do build/build_publish.py gom.
set -e

# 1) Cấu hình service (user/host/port) — fresh vs upgrade.
#    AUTOAI_ENV: file env cho unit systemd (EnvironmentFile=-/etc/autoai/.env).
#    - UPGRADE (file đã tồn tại): GIỮ cấu hình cũ — không hỏi, không ghi đè.
#    - FRESH (file thiếu): hỏi qua debconf nếu có, không có thì dùng mặc định
#      (USER=autoai, HOST=0.0.0.0, PORT=8700).
AUTOAI_ENV=/etc/autoai/.env
if [ -f "$AUTOAI_ENV" ]; then
    echo "[autoai] $AUTOAI_ENV đã tồn tại — giữ cấu hình cũ (không hỏi, không ghi đè)."
    SERVICE_USER=$(grep -E '^AUTOAI_SERVICE_USER=' "$AUTOAI_ENV" 2>/dev/null | head -n 1 | cut -d= -f2-)
    [ -n "$SERVICE_USER" ] || SERVICE_USER=autoai
else
    SERVICE_USER=autoai
    SERVICE_HOST=0.0.0.0
    SERVICE_PORT=8700
    if command -v debconf-communicate >/dev/null 2>&1; then
        # debconf-communicate trả về cặp "question\nanswer" cho mỗi câu hỏi
        # (3 câu hỏi → 6 dòng; answer nằm ở dòng 2, 4, 6).
        DEBCONF_ANSWERS=$(debconf-communicate autoai <<EOF
autoai/service_user
autoai/service_host
autoai/service_port
EOF
        ) || DEBCONF_ANSWERS=""
        ANSWER_USER=$(printf '%s\n' "$DEBCONF_ANSWERS" | sed -n '2p')
        ANSWER_HOST=$(printf '%s\n' "$DEBCONF_ANSWERS" | sed -n '4p')
        ANSWER_PORT=$(printf '%s\n' "$DEBCONF_ANSWERS" | sed -n '6p')
        if [ -n "$ANSWER_USER" ]; then SERVICE_USER=$ANSWER_USER; fi
        if [ -n "$ANSWER_HOST" ]; then SERVICE_HOST=$ANSWER_HOST; fi
        if [ -n "$ANSWER_PORT" ]; then SERVICE_PORT=$ANSWER_PORT; fi
    fi
fi

# 2) Tạo user system đã chọn nếu chưa có (mặc định 'autoai' — giữ hành vi cũ).
if ! id -u "$SERVICE_USER" >/dev/null 2>&1; then
    useradd --system --shell /usr/sbin/nologin "$SERVICE_USER"
    echo "[autoai] Đã tạo user system '$SERVICE_USER'."
fi

# 3) Tạo venv + cài dependencies — bước này chạy LÚC CÀI.
#    LƯU Ý: nếu máy offline / pip lỗi mạng → KHÔNG fail cả cài đặt,
#    chỉ WARN và in hướng dẫn chạy tay (cho phép install tiếp).
VENV_DIR=/opt/autoai/venv
if [ ! -x "$VENV_DIR/bin/python" ]; then
    python3 -m venv "$VENV_DIR"
    echo "[autoai] Đã tạo venv tại $VENV_DIR."
fi
"$VENV_DIR/bin/pip" install --upgrade pip -q \
    || echo "[autoai] WARN: không upgrade được pip (có thể mất mạng). Chạy tay sau: sudo $VENV_DIR/bin/pip install --upgrade pip"
"$VENV_DIR/bin/pip" install -q -r /opt/autoai/lib/requirements.txt \
    || { echo "[autoai] WARN: pip install requirements lỗi (có thể mất mạng)."; \
         echo "[autoai] Chạy tay sau khi có mạng: sudo $VENV_DIR/bin/pip install -r /opt/autoai/lib/requirements.txt"; }

# 4) Copy .env.example (mẫu 2 nền tảng) vào /etc/autoai nếu chưa có.
#    File nằm sẵn trong package tại /opt/autoai/.env.example (build_publish.py
#    copy từ repo root vào vị trí đó — convention dpkg: file đã unpack trước postinst).
#    CHỈ copy nếu chưa tồn tại — giữ file user đã sửa (onlyifdoesntexist).
if [ -f /etc/autoai/.env.example ]; then
    echo "[autoai] .env.example đã tồn tại tại /etc/autoai — bỏ qua (không ghi đè)."
elif [ -f /opt/autoai/.env.example ]; then
    mkdir -p /etc/autoai
    cp /opt/autoai/.env.example /etc/autoai/.env.example
    chown root:root /etc/autoai/.env.example
    chmod 644 /etc/autoai/.env.example
    echo "[autoai] Đã copy .env.example -> /etc/autoai/.env.example (user: cp .env.example .env rồi sửa)."
else
    echo "[autoai] WARN: không thấy /opt/autoai/.env.example trong package — bỏ qua (tạo tay từ mẫu repo nếu cần)."
fi

# 5) Ghi $AUTOAI_ENV — CHỈ khi fresh (upgrade giữ file cũ, xem bước 1).
#    3 biến AUTOAI_SERVICE_* cho unit systemd (User= + HOST/PORT).
#    APPEND (không ghi đè): .env có thể đã có sẵn (user tạo từ .env.example
#    trước khi chạy bước này) — chỉ thêm dòng nào CHƯA có trong file.
if [ ! -f "$AUTOAI_ENV" ]; then
    mkdir -p /etc/autoai
    touch "$AUTOAI_ENV"
    grep -q '^AUTOAI_SERVICE_USER='  "$AUTOAI_ENV" || printf 'AUTOAI_SERVICE_USER=%s\n'  "$SERVICE_USER" >> "$AUTOAI_ENV"
    grep -q '^AUTOAI_SERVICE_HOST='  "$AUTOAI_ENV" || printf 'AUTOAI_SERVICE_HOST=%s\n'  "$SERVICE_HOST" >> "$AUTOAI_ENV"
    grep -q '^AUTOAI_SERVICE_PORT='  "$AUTOAI_ENV" || printf 'AUTOAI_SERVICE_PORT=%s\n'  "$SERVICE_PORT" >> "$AUTOAI_ENV"
    chown root:root "$AUTOAI_ENV"
    chmod 644 "$AUTOAI_ENV"
    echo "[autoai] Đã cập nhật $AUTOAI_ENV (user=$SERVICE_USER, host=$SERVICE_HOST, port=$SERVICE_PORT)."
fi

# 6) Cài unit systemd — chỉ ghi đè + daemon-reload khi unit cũ KHÁC user mới
#    (hoặc chưa có unit). Unit mới đọc User= từ $AUTOAI_ENV (EnvironmentFile),
#    nên unit dạng mới (User=${AUTOAI_SERVICE_USER...}) được coi là ĐÃ KHỚP.
UNIT_PATH=/etc/systemd/system/autoai.service
if command -v systemctl >/dev/null 2>&1; then
    if [ -f /opt/autoai/deploy/autoai.service ]; then
        UNIT_MATCHES=0
        if [ -f "$UNIT_PATH" ]; then
            if grep -q "^User=${SERVICE_USER}\$" "$UNIT_PATH" 2>/dev/null; then
                UNIT_MATCHES=1
            elif grep -q '^User=\${AUTOAI_SERVICE_USER' "$UNIT_PATH" 2>/dev/null; then
                UNIT_MATCHES=1
            fi
        fi
        if [ "$UNIT_MATCHES" = "1" ]; then
            echo "[autoai] Unit systemd đã khớp user '$SERVICE_USER' — bỏ qua (không daemon-reload)."
        else
            install -m 644 /opt/autoai/deploy/autoai.service "$UNIT_PATH"
            systemctl daemon-reload || true
        fi
    else
        echo "[autoai] WARN: không thấy /opt/autoai/deploy/autoai.service trong package — bỏ qua bước cài unit."
    fi
else
    echo "[autoai] WARN: không có systemctl — bỏ qua bước cài unit."
fi

# 7) chown code/dữ liệu cho user đã chọn (service chạy bằng user này).
chown -R "${SERVICE_USER}:" /opt/autoai

# 8) KHÔNG tự enable/start service trong postinst — an toàn cho chroot/first-boot
#    (systemd có thể chưa chạy trong môi trường cài đặt, tự start dễ fail cả gói).
echo "[autoai] Cài đặt xong. Bật service bằng: sudo systemctl enable --now autoai"
