#!/bin/bash

# ====================================================
# Script: deploy_idste_v0810.sh
# Target: Ubuntu 22.04 (Jammy)
# Usage: curl -s https://leyu.net.cn/scripts/deploy_idste.sh | sudo bash
# ====================================================

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

clear
echo -e "${YELLOW}>>> IDSTE Server R08.10 自动安装程序 / Auto Installer <<<${NC}"
sleep 1

echo -e "\n${GREEN}[1/5] 正在配置阿里云镜像源...${NC}"
echo -e "      Configuring Aliyun APT mirrors..."
[ -f /etc/apt/sources.list ] && sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo bash -c 'cat <<EOT > /etc/apt/sources.list
deb http://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse
EOT'

if [ $? -eq 0 ]; then
    echo -e "✅ 镜像源已更新 / Mirrors updated."
else
    echo -e "${RED}❌ 换源失败 / Failed to update mirrors.${NC}"
    exit 1
fi
sleep 2

echo -e "\n${GREEN}[2/5] 正在下载 IDSTE 初始化脚本...${NC}"
echo -e "      Downloading IDSTE initialization script..."
wget -q http://mirrors.idste.org/ubuntu/public/idste-install.sh -O idste-install.sh
if [ $? -eq 0 ]; then
    echo -e "✅ 下载完成 / Download complete."
    chmod +x idste-install.sh
else
    echo -e "${RED}❌ 下载失败 / Download failed.${NC}"
    exit 1
fi
sleep 2

echo -e "\n${GREEN}[3/5] 正在执行环境初始化...${NC}"
echo -e "      Running environment initialization..."
sudo ./idste-install.sh
if [ $? -eq 0 ]; then
    echo -e "✅ 初始化完毕 / Initialization finished."
else
    echo -e "${RED}❌ 初始化出错 / Initialization error.${NC}"
    exit 1
fi
sleep 2

echo -e "\n${GREEN}[4/5] 正在安装 IDSTE Server...${NC}"
echo -e "      Installing idste-server-0810..."
sudo apt update -y
sudo apt install -y idste-server-0810
sleep 2

echo -e "\n${GREEN}[5/5] 正在验证安装状态...${NC}"
echo -e "      Verifying installation status..."
if dpkg -l | grep -q "idste-server-0810"; then
    echo -e "\n${GREEN}===============================================${NC}"
    echo -e "${GREEN}  🎉 安装成功！ / Installation Successful!      ${NC}"
    echo -e "${GREEN}  版本 / Version: R08.10                       ${NC}"
    echo -e "${GREEN}===============================================${NC}"
else
    echo -e "${RED}❌ 安装失败，请检查报错 / Installation failed.${NC}"
    exit 1
fi

rm -f idste-install.sh
