#!/bin/bash

set -e

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

# 获取当前目录
CURRENT_DIR=$(pwd)
PACKAGE_NAME="node-exporter-$(date +%Y%m%d-%H%M%S)"
PACKAGE_FILE="${PACKAGE_NAME}.tar.gz"

log_info "开始打包 Node Exporter 安装包..."

# 检查必要文件
log_info "检查必要文件..."

required_files=(
    "install.sh"
    "uninstall.sh"
    "bin/node_exporter"
    "check_health.sh"
)

missing_files=()
for file in "${required_files[@]}"; do
    if [[ ! -f "$file" ]]; then
        missing_files+=("$file")
    fi
done

if [[ ${#missing_files[@]} -gt 0 ]]; then
    echo "缺少以下文件:"
    for file in "${missing_files[@]}"; do
        echo "  - $file"
    done
    exit 1
fi

log_success "所有必要文件检查完成"

# 创建临时目录
TEMP_DIR=$(mktemp -d)
log_info "创建临时目录: $TEMP_DIR"

# 复制文件到临时目录
cp -r . "$TEMP_DIR/$PACKAGE_NAME"

# 进入临时目录
cd "$TEMP_DIR"

# 创建压缩包
log_info "创建压缩包: $PACKAGE_FILE"
tar -czf "$PACKAGE_FILE" "$PACKAGE_NAME"

# 移动压缩包到原目录
mv "$PACKAGE_FILE" "$CURRENT_DIR/"

# 清理临时目录
rm -rf "$TEMP_DIR"

# 返回原目录
cd "$CURRENT_DIR"

# 显示结果
log_success "打包完成！"
echo
echo "安装包文件: $PACKAGE_FILE"
echo "文件大小: $(du -h "$PACKAGE_FILE" | cut -f1)"
echo
echo "使用方法:"
echo "1. 将 $PACKAGE_FILE 传输到目标服务器"
echo "2. 解压: tar -xzf $PACKAGE_FILE"
echo "3. 进入目录: cd $PACKAGE_NAME"
echo "4. 运行安装: sudo ./install.sh"
echo
echo "注意: 请确保所有必要文件都存在"
