#!/bin/bash
# 用于生成preinst脚本的辅助脚本
# $1: 软件包名（例如 bianbu-star-config）
# $2: overlay目录（例如 star）


PACKAGE=$1
VARIANT=$2
OUTPUT_FILE="debian/${PACKAGE}.preinst"

# 创建脚本基本结构
cat > "$OUTPUT_FILE" << 'EOL'
#!/bin/bash
set -e

BACKUP_DIR="/var/lib/bianbu-config/backup"

# 备份系统中已存在的将被覆盖的文件
backup_files() {
    mkdir -p "$BACKUP_DIR"
    
    # 预定义的文件列表
    local overlay_files=(
EOL

# 添加文件列表，一行一个文件，确保引号完整
if [ -d "target_overlay/$VARIANT" ] && [ "$(find "target_overlay/$VARIANT" -type f | wc -l)" -gt 0 ]; then
    find "target_overlay/$VARIANT" -type f | while read -r file; do
        rel_path=${file#target_overlay/$VARIANT}
        echo "        \"$rel_path\"" >> "$OUTPUT_FILE"
    done
else
    echo "        \"/var/lib/bianbu-config/placeholder\"" >> "$OUTPUT_FILE"
fi

# 继续添加后续的脚本内容
cat >> "$OUTPUT_FILE" << 'EOL'
    )

    for file in "${overlay_files[@]}"; do
        if [ "$file" != "/var/lib/bianbu-config/placeholder" ] && [ -f "$file" ]; then
            # 创建备份目录
            mkdir -p "$BACKUP_DIR/$(dirname "$file")"
            # 备份文件
            cp -a "$file" "$BACKUP_DIR$file"
            echo "Backed up: $file to $BACKUP_DIR$file"
        fi
    done
}

# 确保在所有情况下都执行备份
case "$1" in
    install|upgrade|abort-upgrade)
        echo "Running backup for $1 action"
        backup_files
        ;;
    *)
        echo "preinst called with unknown argument \"$1\""
        backup_files  # 始终尝试执行备份
        ;;
esac

#DEBHELPER#
exit 0
EOL

chmod +x "$OUTPUT_FILE"
echo "Generated $OUTPUT_FILE for $VARIANT"
