#!/bin/bash

cd /root >/dev/null 2>&1

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

REGEX=("debian|astra" "ubuntu")
RELEASE=("Debian" "Ubuntu")
CMD=("$(grep -i pretty_name /etc/os-release 2>/dev/null | cut -d \" -f2)" "$(lsb_release -sd 2>/dev/null)")
SYS="${CMD[0]}"
[[ -n $SYS ]] || exit 1

for ((int = 0; int < ${#REGEX[@]}; int++)); do
    if [[ $(echo "$SYS" | tr '[:upper:]' '[:lower:]') =~ ${REGEX[int]} ]]; then
        SYSTEM="${RELEASE[int]}"
        [[ -n $SYSTEM ]] && break
    fi
done

if [[ "$SYSTEM" != "Debian" && "$SYSTEM" != "Ubuntu" ]]; then
    echo -e "${RED}[ERR]${NC} 此脚本仅支持 Debian 和 Ubuntu 系统"
    exit 1
fi

if [[ "$SYSTEM" == "Debian" ]]; then
    OS_VERSION=$(cat /etc/debian_version | cut -d. -f1)
elif [[ "$SYSTEM" == "Ubuntu" ]]; then
    OS_VERSION=$(grep VERSION_ID /etc/os-release | cut -d'"' -f2 | cut -d. -f1)
fi

RECOMMENDED=false
if [[ "$SYSTEM" == "Debian" && ("$OS_VERSION" == "12" || "$OS_VERSION" == "13") ]]; then
    RECOMMENDED=true
elif [[ "$SYSTEM" == "Ubuntu" && ("$OS_VERSION" == "24" || "$OS_VERSION" == "25") ]]; then
    RECOMMENDED=true
fi

if [[ "$RECOMMENDED" != "true" ]]; then
    warn "当前系统: $SYSTEM $OS_VERSION"
    warn "推荐使用: Debian 12/13 或 Ubuntu 24/25"
    reading "是否继续安装？(y/n) [n]：" confirm_install
    confirm_install=${confirm_install:-n}
    [[ "$confirm_install" =~ ^[yY]$ ]] || exit 1
fi

log()  { echo -e "$1"; }
ok()   { log "${GREEN}[OK]${NC} $1"; }
info() { log "${BLUE}[INFO]${NC} $1"; }
warn() { log "${YELLOW}[WARN]${NC} $1"; }
err()  { log "${RED}[ERR]${NC} $1"; exit 1; }

reading() { read -rp "$(echo -e "${GREEN}$1${NC}")" "$2"; }

install_package() {
    dpkg -l | grep -q "^ii.*$1" && return
    apt-get install -y "$1" >/dev/null 2>&1 || apt-get install -y "$1" --fix-missing >/dev/null 2>&1
}

get_available_space() {
    df -BG / | awk 'NR==2 {gsub("G","",$4); print $4}'
}

install_lxd() {
    install_package nftables
    install_package snapd

    export PATH=$PATH:/snap/bin

    if ! command -v lxc >/dev/null 2>&1; then
        snap install lxd --channel=latest/stable
        snap alias lxd.lxc lxc
    fi

    snap set lxd lxcfs.flags="-l"
    snap restart lxd
    sleep 3
}

init_lxd_network() {
    lxc network show lxdbr0 >/dev/null 2>&1 || lxc network create lxdbr0
    lxc profile device add default eth0 nic network=lxdbr0 || true
}

setup_storage() {
    lxc storage show default >/dev/null 2>&1 && return

    size=$(get_available_space)
    reading "请输入存储池大小(GB) [$size]：" pool_size
    pool_size=${pool_size:-$size}

    lxc storage create default dir size=${pool_size}GB
    lxc profile device add default root disk path=/ pool=default
}

deploy_lxdapi() {
    info "下载 LXDAPI..."
    rm -f /root/lxdapi.tar.gz
    wget -O /root/lxdapi.tar.gz http://cccimg.com/down.php/26d5c8f2000a90d87077378e06aed883.gz
    mkdir -p /opt/lxdapi
    tar -xzf /root/lxdapi.tar.gz -C /opt/lxdapi --strip-components=1
    ok "LXDAPI 部署完成"
}

configure_lxdapi() {
    info "配置 LXDAPI..."
    cf="/opt/lxdapi/configs/config.yaml"

    reading "服务端口 [8443]：" port
    port=${port:-8443}

    apikey=$(openssl rand -hex 16)
    admin_user="admin"
    admin_pass=$(openssl rand -hex 8)

    sed -i "s|__SERVER_PORT__|$port|g" "$cf"
    sed -i "s|__API_HASH__|$apikey|g" "$cf"
    sed -i "s|__ADMIN_USER__|$admin_user|g" "$cf"
    sed -i "s|__ADMIN_PASS__|$admin_pass|g" "$cf"
    sed -i "s|__SESSION_SECRET__|$(openssl rand -hex 16)|g" "$cf"
    sed -i "s|__TASK_BACKEND__|memory|g" "$cf"
    sed -i "s|__DB_TYPE__|sqlite|g" "$cf"

    ok "LXDAPI 配置完成"
}

setup_lxdapi_service() {
    cat > /etc/systemd/system/lxdapi.service << EOF
[Unit]
Description=LXD API Server
After=network.target lxd.service

[Service]
Type=simple
ExecStart=/opt/lxdapi/lxdapi-amd64
Restart=always

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable lxdapi
    systemctl start lxdapi
    sleep 5
}

import_lxd_images() {
    info "检查并导入 LXD 镜像..."

    images=(
        "debian12|https://api.gitproxy.dev/github.com/xkatld/zjmf-lxd-server/releases/download/images/debian12-amd64.tar.gz"
        "debian13|https://api.gitproxy.dev/github.com/xkatld/zjmf-lxd-server/releases/download/images/debian13-amd64.tar.gz"
        "ubuntu2404|https://api.gitproxy.dev/github.com/xkatld/zjmf-lxd-server/releases/download/images/ubuntu2404-amd64.tar.gz"
    )

    for entry in "${images[@]}"; do
        name="${entry%%|*}"
        url="${entry##*|}"

        if lxc image list | grep -q "$name"; then
            ok "镜像已存在: $name"
            continue
        fi

        info "下载镜像: $name"
        wget -O "/root/${name}.tar.gz" "$url" >/dev/null 2>&1 || {
            warn "$name 下载失败"
            continue
        }

        lxc image import "/root/${name}.tar.gz" --alias "$name"
        rm -f "/root/${name}.tar.gz"
        ok "$name 导入完成"
    done
}

main() {
    echo
    echo "======== 1/5 安装 LXD ========"
    install_lxd

    echo
    echo "======== 2/5 网络配置 ========"
    init_lxd_network

    echo
    echo "======== 3/5 存储配置 ========"
    setup_storage

    echo
    echo "======== 4/5 安装 LXDAPI ========"
    deploy_lxdapi
    configure_lxdapi
    setup_lxdapi_service

    echo
    echo "======== 5/5 导入 LXD 镜像 ========"
    import_lxd_images

    echo
    echo "========================================"
    echo "        安装全部完成"
    echo "========================================"
    echo
    info "LXDAPI 端口: $port"
    info "API Key: $apikey"
    info "管理员: $admin_user / $admin_pass"
    info "已导入镜像: debian12 debian13 ubuntu2404"
}

main
