#!/bin/bash

# 一键安装脚本 - ARM Ubuntu版本
echo "========================================"
echo "  DZXJ DTU 应用一键安装脚本 (ARM Ubuntu)  "
echo "========================================"

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查是否在ARM平台
if [[ $(uname -m) != "aarch64" && $(uname -m) != "armv7l" && $(uname -m) != "armv8l" ]]; then
    echo -e "${RED}错误: 此安装脚本仅适用于ARM架构的Ubuntu系统${NC}"
    echo -e "当前系统架构: $(uname -m)"
    exit 1
fi

# 检查是否是Ubuntu系统
if ! command -v lsb_release &> /dev/null || [[ ! $(lsb_release -i 2>/dev/null) =~ Ubuntu ]]; then
    echo -e "${YELLOW}警告: 此脚本针对Ubuntu系统优化，您的系统可能不受完全支持${NC}"
    read -p "是否继续安装? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# 检查是否为root用户并调整安装目录
if [ "$EUID" -eq 0 ]; then
    echo -e "${YELLOW}警告: 正在以root用户运行脚本${NC}"
    # 为root用户设置不同的安装目录
    INSTALL_DIR="/opt/dzxj_dtu"
    echo -e "${GREEN}将使用 /opt/dzxj_dtu 作为安装目录${NC}"
else
    INSTALL_DIR="$HOME/dzxj_dtu"
fi

# 创建安装目录
INSTALL_DIR="$HOME/dzxj_dtu"
if [ -d "$INSTALL_DIR" ]; then
    echo -e "${YELLOW}警告: 安装目录已存在$INSTALL_DIR${NC}"
    echo -e "${GREEN}自动覆盖现有安装目录...${NC}"
    rm -rf "$INSTALL_DIR"
fi

mkdir -p "$INSTALL_DIR"
echo -e "${GREEN}创建安装目录: $INSTALL_DIR${NC}"

# 配置apt-get使用阿里源
echo -e "${GREEN}配置apt-get使用阿里源...${NC}"
ARCH=$(dpkg --print-architecture)
CODENAME=$(lsb_release -cs)

# 备份原有源文件
if [ ! -f /etc/apt/sources.list.bak ]; then
    sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
    echo -e "${GREEN}已备份原有源文件到 /etc/apt/sources.list.bak${NC}"
fi

# 配置阿里源
echo -e "${GREEN}设置阿里源...${NC}"
sudo tee /etc/apt/sources.list > /dev/null << EOF
deb http://mirrors.aliyun.com/ubuntu-ports/ $CODENAME main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu-ports/ $CODENAME main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu-ports/ $CODENAME-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu-ports/ $CODENAME-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu-ports/ $CODENAME-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu-ports/ $CODENAME-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu-ports/ $CODENAME-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu-ports/ $CODENAME-backports main restricted universe multiverse
EOF

# 安装系统依赖
 echo -e "${GREEN}安装系统依赖...${NC}"
 sudo apt-get update
 
 # 检查并安装nginx
 echo -e "${GREEN}检查nginx安装状态...${NC}"
 if ! command -v nginx &> /dev/null; then
     echo -e "${YELLOW}nginx未安装，正在安装...${NC}"
     sudo apt-get install -y nginx
     if [ $? -eq 0 ]; then
         echo -e "${GREEN}nginx安装成功${NC}"
     else
         echo -e "${RED}错误: nginx安装失败${NC}"
         exit 1
     fi
 else
     echo -e "${GREEN}nginx已安装${NC}"
 fi
 
 # 安装其他依赖
 sudo apt-get install -y --no-install-recommends \
     python3 python3-venv python3-pip python3-dev \
     gcc libffi-dev make \
     git curl \
     net-tools iproute2 \
     mosquitto mosquitto-clients \
     libgpiod2 libgpiod-dev

if [ $? -ne 0 ]; then
    echo -e "${RED}错误: 系统依赖安装失败${NC}"
    exit 1
fi

# 设置npm镜像源为阿里源以加速（如果需要在目标机器上构建）
# echo -e "${GREEN}配置npm镜像源...${NC}"
# npm config set registry https://registry.npmmirror.com --global

# 复制项目文件到安装目录
echo -e "${GREEN}复制项目文件...${NC}"
cp -r "$(pwd)/backend" "$INSTALL_DIR/"

# 复制前端预编译的dist目录
echo -e "${GREEN}复制前端预编译文件...${NC}"
mkdir -p "$INSTALL_DIR/frontend"

# 检查是否存在dist目录
if [ -d "$(pwd)/frontend/dist" ]; then
    cp -r "$(pwd)/frontend/dist" "$INSTALL_DIR/frontend/" || echo -e "${YELLOW}警告: 复制frontend/dist失败${NC}"
    echo -e "${GREEN}已复制前端预编译文件到 $INSTALL_DIR/frontend/dist${NC}"
else
    echo -e "${YELLOW}警告: 未找到前端预编译的dist目录${NC}"
    echo -e "${YELLOW}请先在本地执行 npm install && npm run build 构建前端${NC}"
fi

# 创建Python虚拟环境
echo -e "${GREEN}创建Python虚拟环境...${NC}"
python3 -m venv "$INSTALL_DIR/venv"

# 激活虚拟环境
source "$INSTALL_DIR/venv/bin/activate"

# 升级pip并设置镜像源
pip install --upgrade pip
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/

# 安装Python依赖
echo -e "${GREEN}安装Python依赖...${NC}"
pip install --no-cache-dir -r "$INSTALL_DIR/backend/requirements.txt"

if [ $? -ne 0 ]; then
    echo -e "${RED}错误: Python依赖安装失败${NC}"
    exit 1
fi

# 配置nginx部署前端
echo -e "${GREEN}配置nginx部署前端...${NC}"

# 创建nginx配置文件
NGINX_CONF="dzxj_dtu.conf"
sudo tee "/etc/nginx/sites-available/$NGINX_CONF" > /dev/null << EOF
server {
    listen 80;
    server_name localhost;

    # 前端静态文件目录
    root $INSTALL_DIR/frontend/dist;
    index index.html;

    location / {
        try_files \$uri \$uri/ /index.html;
    }

    # 代理后端API请求
    location /api {
        proxy_pass http://localhost:5001/api;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    # WebSocket连接代理
    location /socket.io {
        proxy_pass http://localhost:5001/socket.io;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}
EOF

# 启用nginx配置
if [ -f /etc/nginx/sites-enabled/default ]; then
    sudo rm /etc/nginx/sites-enabled/default
    echo -e "${GREEN}已移除默认nginx配置${NC}"
fi

sudo ln -sf /etc/nginx/sites-available/$NGINX_CONF /etc/nginx/sites-enabled/
echo -e "${GREEN}已启用nginx配置: $NGINX_CONF${NC}"

# 测试nginx配置并重启
sudo nginx -t
if [ $? -eq 0 ]; then
    sudo systemctl restart nginx
    echo -e "${GREEN}nginx服务已重启，前端部署成功${NC}"
else
    echo -e "${RED}错误: nginx配置有误，请检查${NC}"
fi

# 编译 DHT11 C 读取器（如源码存在）
if [ -f "$INSTALL_DIR/backend/scripts/dht11_reader.c" ]; then
    echo -e "${GREEN}编译 DHT11 C 读取器...${NC}"
    if command -v gcc >/dev/null 2>&1 && ldconfig -p | grep -q libgpiod; then
        gcc -O2 -o "$INSTALL_DIR/backend/scripts/dht11_reader" "$INSTALL_DIR/backend/scripts/dht11_reader.c" -lgpiod
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}DHT11 C 读取器编译成功${NC}"
        else
            echo -e "${YELLOW}警告: DHT11 C 读取器编译失败，将回退到 Python gpiod${NC}"
        fi
    else
        echo -e "${YELLOW}警告: 缺少 gcc 或 libgpiod，跳过 DHT11 C 读取器编译${NC}"
    fi
fi

# 创建默认环境配置文件（供 systemd EnvironmentFile 使用）
if [ ! -f "/etc/default/dzxj_dtu" ]; then
    echo -e "${GREEN}创建默认环境配置文件 /etc/default/dzxj_dtu...${NC}"
    cat > /etc/default/dzxj_dtu << 'EOF'
DHT11_ENABLED=true
DHT11_GPIO_PIN=19
DHT11_GPIO_CHIP=gpiochip0
DHT11_POLL_INTERVAL=5
DHT11_SIMULATE=false
EOF
    chmod 644 /etc/default/dzxj_dtu
fi

# 创建启动脚本
echo -e "${GREEN}创建启动脚本...${NC}"
cat > "$INSTALL_DIR/start.sh" << 'EOF'
#!/bin/bash

# 启动脚本
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

echo -e "${GREEN}启动DZXJ DTU应用...${NC}"

# 确保脚本在正确的目录下执行
cd "$(dirname "$0")"

# 激活虚拟环境
source "venv/bin/activate"

# 加载环境变量
export TZ=Asia/Shanghai
if [ -f /etc/default/dzxj_dtu ]; then
    set -a
    source /etc/default/dzxj_dtu
    set +a
fi

# 进入后端目录
cd backend

# 检查端口是否已被占用
if lsof -Pi :5001 -sTCP:LISTEN -t >/dev/null ; then
    echo -e "${YELLOW}警告: 端口5001已被占用${NC}"
    read -p "是否继续启动? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo -e "${GREEN}应用启动中，访问地址: http://localhost:5001${NC}"
# 启动应用（直接运行 app.py，避免 flask run 与环境变量不兼容的问题）
python app.py
EOF

# 创建停止脚本
echo -e "${GREEN}创建停止脚本...${NC}"
cat > "$INSTALL_DIR/stop.sh" << 'EOF'
#!/bin/bash

# 停止脚本
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

echo -e "${GREEN}停止DZXJ DTU应用...${NC}"

# 查找并停止应用进程
PIDS=$(lsof -Pi :5001 -sTCP:LISTEN -t)
if [ -n "$PIDS" ]; then
    echo -e "${GREEN}停止进程: $PIDS${NC}"
    kill -15 $PIDS
    
    # 等待进程停止
    for pid in $PIDS; do
        echo -e "${GREEN}等待进程 $pid 停止...${NC}"
        wait $pid 2>/dev/null
    done
    
    echo -e "${GREEN}应用已停止${NC}"
else
    echo -e "${YELLOW}没有发现运行中的DZXJ DTU应用${NC}"
fi
EOF

# 创建systemd服务配置（可选）
echo -e "${GREEN}创建systemd服务配置...${NC}"
# 根据运行用户设置适当的配置
if [ "$EUID" -eq 0 ]; then
    # root用户的服务配置
    cat > "$INSTALL_DIR/dzxj_dtu.service" << EOF
[Unit]
Description=DZXJ DTU Application
After=network.target

[Service]
User=root
WorkingDirectory=$INSTALL_DIR/backend
Environment="TZ=Asia/Shanghai"
EnvironmentFile=-/etc/default/dzxj_dtu
ExecStart=$INSTALL_DIR/venv/bin/python app.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
else
    # 普通用户的服务配置
    cat > "$INSTALL_DIR/dzxj_dtu.service" << EOF
[Unit]
Description=DZXJ DTU Application
After=network.target

[Service]
User=$USER
WorkingDirectory=$INSTALL_DIR/backend
Environment="TZ=Asia/Shanghai"
EnvironmentFile=-/etc/default/dzxj_dtu
ExecStart=$INSTALL_DIR/venv/bin/python app.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
fi

# 设置脚本执行权限
chmod +x "$INSTALL_DIR/start.sh"
chmod +x "$INSTALL_DIR/stop.sh"

# 配置开机自启动
echo -e "${GREEN}配置开机自启动...${NC}"
# 复制service文件到systemd目录
sudo cp "$INSTALL_DIR/dzxj_dtu.service" /etc/systemd/system/
if [ $? -eq 0 ]; then
    echo -e "${GREEN}已复制服务配置到 /etc/systemd/system/dzxj_dtu.service${NC}"
    
    # 重新加载systemd配置
    sudo systemctl daemon-reload
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}已重新加载systemd配置${NC}"
        
        # 启用服务
        sudo systemctl enable dzxj_dtu.service
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}已启用dzxj_dtu服务开机自启动${NC}"
            
            # 启动服务
            sudo systemctl start dzxj_dtu.service
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}dzxj_dtu服务已启动${NC}"
            else
                echo -e "${YELLOW}警告: dzxj_dtu服务启动失败，请手动检查${NC}"
            fi
        else
            echo -e "${RED}错误: 启用dzxj_dtu服务失败${NC}"
        fi
    else
        echo -e "${RED}错误: 重新加载systemd配置失败${NC}"
    fi
else
    echo -e "${RED}错误: 复制服务配置失败${NC}"
fi

# 显示安装完成信息
echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}  DZXJ DTU 应用安装完成!  ${NC}"
echo -e "${GREEN}========================================${NC}\n"
echo -e "安装目录: ${GREEN}$INSTALL_DIR${NC}"
echo -e "\n使用方法:"
echo -e "  1. 手动启动应用:"
echo -e "     ${YELLOW}cd $INSTALL_DIR && ./start.sh${NC}"
echo -e "\n  2. 停止应用:"
echo -e "     ${YELLOW}cd $INSTALL_DIR && ./stop.sh${NC}"
echo -e "\n  3. 管理系统服务:"
echo -e "     ${YELLOW}# 查看服务状态"
echo -e "     sudo systemctl status dzxj_dtu.service"
echo -e "     # 重启服务"
echo -e "     sudo systemctl restart dzxj_dtu.service"
echo -e "     # 禁用自启动"
echo -e "     sudo systemctl disable dzxj_dtu.service${NC}"
echo -e "\n  4. 检查nginx状态:"
echo -e "     ${YELLOW}sudo systemctl status nginx${NC}"
echo -e "\n应用访问地址: ${GREEN}http://localhost${NC}"
echo -e "\n${GREEN}安装成功!${NC}"