#!/usr/bin/env bash
#set -euo pipefail

# -------------------------
# Script Name:       myrelease
# Version:           $VER
# Description:       This is a script that reads lpi files and automates
#                    packaging to generate RPM and DEB files. 
# License Agreement: MIT
# Author:            Eric Quan <gasensor@sina.com> 
# Copyright:         Eric Quan <gasensor@sina.com> 
# Website:           www.gasensor.cn
# -------------------------




# -------------------------
# default value
# -------------------------
DEBUG=true
OUTPUT_DIR="./dist"
ZIP=false
KEEP=false
PADDED=false
VER=20260508

# -------------------------
# Global Var
# -------------------------


# -------------------------
# log and display function
# -------------------------
RED='\033[1;31m'
GRN='\033[1;32m'
YLW='\033[1;33m'
BLU='\033[1;34m'
PUR='\033[1;35m'
CYN='\033[1;36m'
WHT='\033[1;37m'
NC='\033[0m' # No Color

log() {
  if [ "$DEBUG" = true ]; then
    echo -e "${GRN}[INF]${NC}[$(basename "$1")] \c "
    shift
    for arg in "$@"; do
      echo -e "$arg\c"
    done
    echo -e ""
  fi
}


err() {
  echo -e "${RED}[ERR]${NC}[$(basename "$1")] \c "
  shift
  for arg in "$@"; do
    echo -e "$arg\c"
  done
  echo -e "" >&2
  exit 1
}


# -------------------------
# Runtime Environment Check
# -------------------------
require_tool() {
  local t="$1"
  if ! command -v "$t" >/dev/null 2>&1; then
    err "" "Required tool ${RED}'$t'${NC} not found. Please install it." >&2
    exit 2
  fi
}

# 检查必要工具
TOOLS=(xmlstarlet dpkg-deb rpmbuild zip fakeroot)
for t in "${TOOLS[@]}"; do
  require_tool "$t" || true
done

# -------------------------
# Help
# -------------------------
usage() {
  cat <<EOF
Usage: $0 [-f file.lpi] [-o output_dir] [-p] [-q] [-z] [-k] [-i] [-c] [-v] [-h]
  -f file.lpi   Specify a single .lpi file (can be used multiple times)
  -o dir        Specify output directory (default ${OUTPUT_DIR})
  -p            Formatting version using a format similar to XXXX-XX-XX
  -q            Set quiet mode, do not show process information
  -z            Compress the output file using zip
  -k            Keep temporary files
  -i            Install to /usr/bin/
  -c            Clean configure file
  -v            Version Information
  -h            Display this information
  
Config file path:  
  project config: {lpi_file}/myrelease.cfg
  system config:  ${HOME}/.config/myrelease/config
    
Default Output Dir:
  {file.lpi}/${OUTPUT_DIR}/
  {file.lpi}/${OUTPUT_DIR}/zip
EOF
  exit 1
}

# -------------------------
# Assist Function
# -------------------------
# xmlstarlet 读取单个 xpath 值（返回空字符串如果不存在）
xml_get() {
  local file="$1"; local xpath="$2"
  xmlstarlet sel -t -v "$xpath" -n "$file" 2>/dev/null || echo ""
}

# 补零函数：pad to width with leading zeros
pad() {
  local val="$1"; local width="$2"
  printf "%0${width}d" "$val"
}

# 简单宏替换：替换 $(ProjectName) $(TargetCPU) $(TargetOS)
expand_macros() {
  local s="$1"; local project="$2"; local cpu="$3"; local os="$4"
  s="${s//\$(ProjectName)/$project}"
  s="${s//\$(TargetCPU)/$cpu}"
  s="${s//\$(TargetOS)/$os}"
  echo "$s"
}

# 转换为 Debian
arch_to_deb() {
  local cpu="$1"
  case "$cpu" in
    i386)       echo "i386" ;;
    x86_64)     echo "amd64" ;;
    arm)        echo "armhf" ;;
    aarch64)    echo "arm64" ;;
    powerpc)    echo "powerpc" ;;
    powerpc64)  echo "ppc64" ;;
    sparc)      echo "sparc" ;;
    sparc64)    echo "sparc64" ;;
    m68k)       echo "m68k" ;;
    mips)       echo "mips" ;;
    mipsel)     echo "mipsel" ;;
    riscv32)    echo "riscv32" ;;
    riscv64)    echo "riscv64" ;;
    *)          echo "unknown" ;;
  esac
}

# 转换为 rpm
arch_to_rpm() {
  local cpu="$1"
  case "$cpu" in
    i386)       echo "i686" ;;   # RPM 常用 i686 表述
    x86_64)     echo "x86_64" ;;
    arm)        echo "arm" ;;
    aarch64)    echo "aarch64" ;;
    powerpc)    echo "ppc" ;;
    powerpc64)  echo "ppc64" ;;
    sparc)      echo "sparc" ;;
    sparc64)    echo "sparc64" ;;
    m68k)       echo "m68k" ;;
    mips)       echo "mips" ;;
    mipsel)     echo "mipsel" ;;
    riscv32)    echo "riscv32" ;;
    riscv64)    echo "riscv64" ;;
    *)          echo "unknown" ;;
  esac
}

# 映射 RPM Group
group_to_rpm() {
  local g="$1"
  case "$g" in
    Network)        echo "Applications/Internet" ;;
    Utility)        echo "Applications/System" ;;
    Development)    echo "Development/Tools" ;;
    Graphics)       echo "Applications/Graphics" ;;
    Multimedia)     echo "Applications/Multimedia" ;;
    Office)         echo "Applications/Productivity" ;;
    System)         echo "System Environment/Base" ;;
    Libraries)      echo "System Environment/Libraries" ;;
    Education)      echo "Applications/Education" ;;
    Games)          echo "Amusements/Games" ;;
    Science)        echo "Applications/Scientific" ;;
    Documentation)  echo "Documentation" ;;
    Fonts)          echo "User Interface/Fonts" ;;
    Accessibility)  echo "Applications/Accessibility" ;;
    Security)       echo "System Environment/Security" ;;
    Database)       echo "Applications/Databases" ;;
    TextEditor)     echo "Applications/Editors" ;;
    Web)            echo "Applications/Internet" ;;
    Mail)           echo "Applications/Internet" ;;
    FileManager)    echo "Applications/File" ;;
    Virtualization) echo "System Environment/Virtualization" ;;
    Hardware)       echo "System Environment/Hardware" ;;
    *)              echo "Unknown RPM Group" ;;
  esac
}

# 映射 Debian Section
group_to_deb() {
  local g="$1"
  case "$g" in
    Network)        echo "net" ;;
    Utility)        echo "utils" ;;
    Development)    echo "devel" ;;
    Graphics)       echo "graphics" ;;
    Multimedia)     echo "sound/video" ;;
    Office)         echo "office" ;;
    System)         echo "admin" ;;
    Libraries)      echo "libs" ;;
    Education)      echo "education" ;;
    Games)          echo "games" ;;
    Science)        echo "science" ;;
    Documentation)  echo "doc" ;;
    Fonts)          echo "fonts" ;;
    Accessibility)  echo "accessibility" ;;
    Security)       echo "security" ;;
    Database)       echo "database" ;;
    TextEditor)     echo "editors" ;;
    Web)            echo "web" ;;
    Mail)           echo "mail" ;;
    FileManager)    echo "fileutils" ;;
    Virtualization) echo "virtualization" ;;
    Hardware)       echo "hardware" ;;
    *)              echo "Unknown Debian Section" ;;
  esac
}

# 映射 Desktop Categories
group_to_desktop() {
  local g="$1"
  case "$g" in
    Network)        echo "Network" ;;
    Utility)        echo "Utility" ;;
    Development)    echo "Development" ;;
    Graphics)       echo "Graphics" ;;
    Multimedia)     echo "AudioVideo" ;;
    Office)         echo "Office" ;;
    System)         echo "System" ;;
    Libraries)      echo "System" ;;
    Education)      echo "Education" ;;
    Games)          echo "Game" ;;
    Science)        echo "Science" ;;
    Documentation)  echo "Documentation" ;;
    Fonts)          echo "Fonts" ;;
    Accessibility)  echo "Accessibility" ;;
    Security)       echo "Security" ;;
    Database)       echo "Database" ;;
    TextEditor)     echo "Utility;TextEditor" ;;
    Web)            echo "WebBrowser" ;;
    Mail)           echo "Email" ;;
    FileManager)    echo "FileManager" ;;
    Virtualization) echo "System" ;;
    Hardware)       echo "HardwareSettings" ;;
    *)              echo "Unknown Desktop Category" ;;
  esac
}

# -------------------------
# Parameter Analysis
# -------------------------
LPI_FILES=()
while getopts "f:o:qz:kicvh" opt; do
  case "$opt" in
    f) LPI_FILES+=("$OPTARG") ;;
    o) OUTPUT_DIR="$OPTARG" ;;
    p) PADDED=true ;;
    q) DEBUG=false ;;
    z) ZIP="$OPTARG" ;;
    i) sudo cp -f "$0" "/usr/bin/myrelease.sh"
       sudo ln -sf "/usr/bin/myrelease.sh" "/usr/bin/myrelease"
       exit 0;;
    c) sudo rm "$HOME/.config/myrelease/config"
       exit 0;; 
    k) KEEP=true ;;
    v) echo $VER 
       exit 0;;
    h) usage ;;
    *) usage ;;
  esac
done
shift $((OPTIND-1))


# -------------------------
# System Default Configure File
# -------------------------
# 默认配置文件
CONFIG_FILE_SYSTEM="$HOME/.config/myrelease/config"

# 如果文件不存在则生成默认文件
if [ ! -f "$CONFIG_FILE_SYSTEM" ]; then
    log "The system config file do not exist"
    mkdir -p "$HOME/.config/myrelease/"
    cat > "$CONFIG_FILE_SYSTEM" <<EOF
# myrelease's configure file
# Values must be enclosed in double quotes! Two consecutive double quotes represent empty
# Author and maintainer's name
AUTHOR="default_author"
# Contact information, usually Email
CONTACT="default@example.com"
# Company or organization name, by default included in the installation path
# If not used, represent empty with two double quotes
COMPANY="default company"
# Website
WEBSITE="www.website.com"
# License agreement, optional: 
# FREE GPL2.1 GPL3.0 AGPL3.0 MIT
LICENSE="FREE"
# Group, for rpm group, debian section, desktop categories
# Group           RPM_Group                         Debian_Section      Desktop_Categories
# Network         Applications/Internet	            net	                Network
# Utility         Applications/System	            utils               Utility
# Development     Development/Tools	            devel               Development
# Graphics        Applications/Graphics	            graphics            Graphics
# Multimedia      Applications/Multimedia           sound / video       AudioVideo
# Office          Applications/Productivity         office              Office
# System          System Environment/Base           admin               System
# Libraries       System Environment/Libraries      libs                System
# Education       Applications/Education            education           Education
# Games           Amusements/Games                  games               Game
# Science         Applications/Scientific           science             Science
# Shells          System Environment/Shells         shells              System
# Documentation   Documentation                     doc                 Documentation
# Fonts           User Interface/Fonts              fonts               Fonts
# Themes          User Interface/Themes             x11                 Settings
# Accessibility   Applications/Accessibility        accessibility       Accessibility
# Security        System Environment/Security       security            Security
# Database        Applications/Databases            database            Database
# Programming     Languages                         Development         Development
# Text            Editors Applications/Editors      editors             Utility / TextEditor
# Web             Applications/Internet             web                 WebBrowser
# Mail            Applications/Internet             mail                Email
# File Management Applications/File                 fileutils           FileManager
# Virtualization  System Environment/Virtualization virtualization      System
# Hardware        System Environment/Hardware       hardware            HardwareSettings
GROUP="Development"
# Depends
DEPENDS_RPM="gtk2"
DEPENDS_DEB="libgtk2.0-0"
EOF
    log "" "The default system config file has been generated. You can find and modify it at the following path"
    log "" "Path: ${PUR}'$CONFIG_FILE_SYSTEM'${NC}"
fi

# -------------------------
# Get System Information
# -------------------------
get_system_info() {
  case "$OSTYPE" in
    linux*)        system_os=linux   ;;
    darwin*)       system_os=macos   ;;
    msys*|cygwin*) system_os=win     ;;
    *)             system_os=unknown ;;
  esac
  system_arch=$(arch)
}

# -------------------------
# Project Configure File
# -------------------------
load_project_config() {
  local lpi="$1"
  # local cfg="$(dirname $(realpath $lpi))/myrelease.cfg"
  local cfg="$(dirname '$lpi')/myrelease.cfg"
  
  # 如果文件不存在则生成默认文件
  if [ ! -f "$cfg" ]; then
    log "lpi" "Project config file does not exist, using system config file instead. You can find and modify it at the following path"
    log "lpi" "$CONFIG_FILE_SYSTEM"
    log "lpi" "$cfg"
    cp $CONFIG_FILE_SYSTEM $cfg 
    log "lpi" "Path: ${PUR}'$cfg'${NC}"
  fi  
  source "$cfg"
}

# -------------------------
# Check Version Information
# -------------------------
check_project_version_information() {
  # 读取 VersionInfo 节点
  local lpi="$1"
  local use_vi
  use_vi="$(xml_get "$lpi" "/CONFIG/ProjectOptions/VersionInfo/UseVersionInfo/@Value")"
  if [ -z "$use_vi" ]; then
    err "$lpi" "Project VersionInfo not found in $lpi"
    return 1
  fi
  if [ "$use_vi" = "false" ] || [ "$use_vi" = "0" ]; then
    err "$lpi" "UseVersionInfo is false in $lpi. Aborting."
    return 1
  fi
}

# -------------------------
# Get Project Info
# -------------------------
get_project_info() {
  local lpi="$1"  
  local major minor rev build i18n
  productname=""
  comments=""
  icon_file=""
  i18n_dir=""
  prefix_dir=""
  
  # 版本信息
  major="$(xml_get "$lpi" "/CONFIG/ProjectOptions/VersionInfo/MajorVersionNr/@Value")"
  minor="$(xml_get "$lpi" "/CONFIG/ProjectOptions/VersionInfo/MinorVersionNr/@Value")"
  rev="$(xml_get "$lpi" "/CONFIG/ProjectOptions/VersionInfo/RevisionNr/@Value")"
  # 默认值保护
  major="${major:-0}"; minor="${minor:-0}"; rev="${rev:-0}"; build="${build:-0}"
  # 补零：Major 4位，Minor 2位，Revision 2位
  if [ PADDED = true ]; then
    major_p="$(pad "$major" 4)"
    minor_p="$(pad "$minor" 2)"
    rev_p="$(pad "$rev" 2)"
  else
    major_p="$major"
    minor_p="$minor"
    rev_p="$rev"
  fi
  # release 使用 BuildNr 原样（通常 1-2 位）
  release="$build"  
  # 组合版本号（可按需调整格式）
  version="${major}.${minor}.${rev}"
  version_s="${major_p}.${minor_p}.${rev_p}"
  version_p="${major_p}.${minor_p}.${rev_p}-$build"
  log "$lpi" "Get Version: ${PUR}'$major.$minor.$rev-$build'${NC}"
  
  #项目名称与简介
  productname="$(xml_get "$lpi" "/CONFIG/ProjectOptions/VersionInfo/StringTable/@ProductName")"
  comments="$(xml_get "$lpi" "/CONFIG/ProjectOptions/VersionInfo/StringTable/@Comments")"
  if [ -z "$productname" ]; then
    productname="$(basename "$lpi" .lpi)"
  fi
  if [ -z "$comments" ]; then
    comments="empty"
  fi
  log "$lpi" "Get productname: ${PUR}'$productname'${NC}"
  log "$lpi" "Get comments: ${PUR}'$comments'${NC}"
  
  # 获取ICO
  icon_file="$(dirname "$lpi")/$(basename "$lpi" .lpi).ico"
  if [ -f "$icon_file" ]; then
    log "$lpi" "Get icon file: ${PUR}'$icon_file'${NC}"
  else
    icon_file=""
    log "$lpi" "Icon file: $icon_file ${PUR}not exist${NC}."
  fi
  
  # i18n
  i18n="$(xmlstarlet sel -t -v "/CONFIG/ProjectOptions/i18n/EnableI18N/@Value" "$lpi")"
  if [ -z "$i18n" ]; then
    log "$lpi" "No i18n setting"
  else
    if [ "$i18n" = "True" ]; then
      i18n_dir="$(dirname "$lpi")/$(xmlstarlet sel -t -v "/CONFIG/ProjectOptions/i18n/OutDir/@Value" "$lpi")"
      if [ -d "$i18n_dir" ]; then
        log "$lpi" "Get i18n dir: ${PUR}'$i18n_dir'${NC}"
      else
        err "$lpi" "${PUR}'$i18n_dir'${NC} Directory does not exist."
      fi
    else
      i18n_dir=""
      log "$lpi" "No i18n setting"
    fi   
  fi
  

  
  # install_prefix
  prefix_dir="${COMPANY}/${productname}"
}



# -------------------------
# Get Build Modes
# -------------------------
get_project_buildmodes_list() {
  local lpi="$1"
  local lps=""
  local xlpi=""
  local tmp=""
  local lpi_cnt=""
  local lps_cnt=""
  local idx=1
  local total
  target_cpu_list=();
  target_os_list=();
  target_filename_list=();
  target_list_count=0;
  
  lpi_cnt="$(xmlstarlet sel -t -v "count(/CONFIG/ProjectOptions/BuildModes/Item)" "$lpi" 2>/dev/null || echo 0)"

  SessionStorage="$(xml_get "$lpi" "/CONFIG/ProjectOptions/General/SessionStorage/@Value")"
  case "$SessionStorage" in
    "")                  ;;
    InProjectDir)        lps="$(basename "$lpi" .lpi).lps" ;;
    InIDEConfig)         lps="$HOME/.lazarus/projectsessions/$(basename "$lpi" .lpi).lps"  ;;
    None)                lps=""     ;;
    *)                   err "$lpi" "${RED}SessionStorage's value:$SessionStorage is unexpected${NC}" ;;
  esac
  
  lps_cnt="$(xmlstarlet sel -t -v "count(/CONFIG/ProjectSession/BuildModes/Item)" "$lps" 2>/dev/null || echo 0)"
 
  if [ "$lpi_cnt" -gt "$lps_cnt" ]; then
    total="$lpi_cnt"
    xlpi="$lpi"
    items_xpath="/CONFIG/ProjectOptions/BuildModes/Item"
  else
    total="$lps_cnt"
    xlpi="$lps"
    items_xpath="/CONFIG/ProjectSession/BuildModes/Item"
  fi
  
  
  if [ -z "$total" ]; then
    err "$lpi" "Not get session info in ${PUR}$lpi${NC} and ${PUR}$lps${NC}."
  fi  
  
  for ((i=1;i<=total;i++)); do
    # 读取 Name 属性
    local name
    name="$(xmlstarlet sel -t -v "($items_xpath)[$i]/@Name" "$xlpi" 2>/dev/null || echo "")"
    if [ "$total" -gt 1 ] && [ "$name" = "Default" ]; then
      log "$lpi" "${PUR}$i/$total${NC} Skipping Default build mode"
      continue
    fi

    # 读取 TargetCPU, TargetOS, Target/Filename
    local target_cpu target_os target_filename
    target_cpu="$(xml_get "$xlpi" "($items_xpath)[$i]/CompilerOptions/CodeGeneration/TargetCPU/@Value")"
    target_os="$(xml_get "$xlpi" "($items_xpath)[$i]/CompilerOptions/CodeGeneration/TargetOS/@Value")"
    if [ -z "$target_cpu" ]; then
      target_cpu="$system_arch";
      log "$lpi" "Item ${PUR}'$name'${NC} target_cpu undefined, using ${PUR}'$system_arch' ${NC}instead."
    fi
    if [ -z "$target_os" ]; then
      target_os="$system_os"
      log "$lpi" "Item ${PUR}'$name'${NC} target_os undefined, using ${PUR}'$system_os' ${NC}instead."
    fi
    
    target_filename="$(xml_get "$xlpi" "($items_xpath)[$i]/CompilerOptions/Target/Filename/@Value")"

    # 如果 target_filename 为空，尝试用项目名
    if [ -z "$target_filename" ]; then
      target_filename="$(basename "$lpi" .lpi)"
    fi

    # 宏替换
    target_filename="$(expand_macros "$target_filename" "$productname" "$target_cpu" "$target_os")"

    # 归一化 arch 与 os
    local arch_rpm
    #arch_rpm="$(arch_rpm_normalize "$target_cpu")"
    local arch_deb
    #arch_deb="$(arch_deb_map "$target_cpu")"
    
    # Win增加.exe
    if [[ "$target_os" == win* ]]; then
      target_filename="${target_filename}.exe"
    fi
    
    # Add element
    target_os_list+=("$target_os");
    target_cpu_list+=("$target_cpu");
    target_filename_list+=("$target_filename");
    target_list_count=$((target_list_count+1));

    log "$lpi" "${PUR}$i/$total${NC} Adding [$name] CPU:$target_cpu OS:$target_os F:$target_filename"
  done
}


# -------------------------
# Build Linux Deb
# -------------------------
build_project_linux_deb() {
  local lpi="$1"
  local x=$2
  local control_file=""
  local desktop_file=""
  local arch=$(arch_to_deb "${target_cpu_list[$x]}" )
  local size=""
  
  local debdir="$tmpdir/${target_cpu_list[$x]}_${target_os_list[$x]}_deb"
  local instdir="/opt/${prefix_dir}"
  
  log "$lpi" "${PUR}Linux deb Started${NC}"
  

  # Deb Dir
  mkdir -p $debdir/{DEBIAN,"$instdir",usr/share/applications,usr/share/icons}
  # Files: EXE
  cp "$prjdir/${target_filename_list[$x]}" "$debdir/$instdir/"
  # Files: ICO
  if [ -n "$icon_file" ]; then
    cp "$icon_file" "$debdir/usr/share/icons/"
  fi
  # Files: i18n
  if [ -n "$i18n_dir" ]; then
    mkdir -p "$debdir$instdir"/$(basename "$i18n_dir")
    cp "$i18n_dir"/*.po "$debdir$instdir"/$(basename "$i18n_dir")
  fi
  # Files: desktop
  desktop_file="$debdir/usr/share/applications/$productname.desktop"
  cat>$desktop_file<<EOF
[Desktop Entry]
Version=$version_p
Name=$productname
GenericName=$productname
Comment=$comments
Type=Application
Exec="$instdir/${target_filename_list[$x]}"
Icon=/usr/share/icons/$(basename "$icon_file")
Keywords=$productname
Categories=$(group_to_desktop "$GROUP")
Name[en_US]=$productname
EOF

  # Size
  size=$(du -sk $debdir | cut -f1)
  
  # Files: control
  control_file="$debdir/DEBIAN/control"
  cat>$control_file<<EOF
Package: $productname
Version: $version_p
Section: $(group_to_deb "$GROUP")
Priority: extra
Architecture: $arch
Depends: $DEPENDS_RPM
Installed-Size: $size
Maintainer: $AUTHOR <$CONTACT>
Homepage: $WEBSITE
Description: $comments
EOF
  
  # build
  dpkg -b "$debdir" "$outdir/$productname.$version_p.${target_os_list[$x]}_${target_cpu_list[$x]}.deb"
  
  if [ "$ZIP" = true ]; then
    mkdir -p "$outdir/zip"
    zip -j "$outdir/zip/$productname.$version_p.${target_os_list[$x]}_${target_cpu_list[$x]}.zip" "$outdir/$productname.$version_p.${target_os_list[$x]}_${target_cpu_list[$x]}.deb" 
  fi

  log "$lpi" "${PUR}Linux deb Finished${NC}"
}

# -------------------------
# Build Linux rpm
# -------------------------
build_project_linux_rpm() {
  local lpi="$1"
  local x=$2
  local control_file=""
  local desktop_file=""
  local arch=$(arch_to_rpm "${target_cpu_list[$x]}" )
  
  local rpmdir="$tmpdir/${target_cpu_list[$x]}_${target_os_list[$x]}_rpm"
  local instdir="/opt/${prefix_dir}"
  
  log "$lpi" "${PUR}Linux rpm Started${NC}"
  
  # Rpm Dir
  mkdir -p $rpmdir/{BUILD/$productname,BUILDROOT,RPMS,SOURCES,SPECS,SPROMS}
  mkdir -p $rpmdir/BUILD/$productname/{ico,bin,i18n,desktop}
  # "."$PROJECT_OS"."$PROJECT_ARCH_RPM
  # Files: EXE
  cp "$prjdir/${target_filename_list[$x]}" "$rpmdir/BUILD/$productname/bin"
  # Files: ICO
  if [ -n "$icon_file" ]; then
    cp "$icon_file" "$rpmdir/BUILD/$productname/ico"
  fi
  # Files: i18n
  if [ -n "$i18n_dir" ]; then
    cp "$i18n_dir"/*.po "$rpmdir/BUILD/$productname/i18n"
  fi
  # Files: desktop
  desktop_file="$rpmdir/BUILD/$productname/desktop/$productname.desktop"
  cat>$desktop_file<<EOF
[Desktop Entry]
Version=$version_p
Name=$productname
GenericName=$productname
Comment=$comments
Type=Application
Exec="$instdir/${target_filename_list[$x]}"
Icon=/usr/share/icons/$(basename "$icon_file")
Keywords=$productname
Categories=$(group_to_desktop "$GROUP")
Name[en_US]=$productname
EOF
  # Files: spec
  spec_file="$rpmdir/SPECS/$productname.spec"
  
cat>$spec_file<<EOF
Name: $productname
Version: $version_s
Release: $release
Requires: $DEPENDS_RPM
License: $LICENSE
Group: $(group_to_deb "$GROUP")
Vendor: $AUTHOR <$CONTACT>
URL: $WEBSITE
Summary: $productname

%description 
$comments

 
%prep 
 
%build 


%install 
mkdir -p \$RPM_BUILD_ROOT/opt/$productname
mkdir -p \$RPM_BUILD_ROOT/usr/share/applications
mkdir -p \$RPM_BUILD_ROOT/usr/share/icons
cd \$RPM_BUILD_DIR

cp -R ../BUILD/"$productname"/bin/* \$RPM_BUILD_ROOT/opt/$productname/
cp -R ../BUILD/"$productname"/desktop/"$productname".desktop \$RPM_BUILD_ROOT/usr/share/applications/"$productname".desktop  
cp -R ../BUILD/"$productname"/ico/$(basename "$icon_file") \$RPM_BUILD_ROOT/usr/share/icons/$(basename "$icon_file")  

%files 
/opt/$productname/
/usr/share/applications/$productname.desktop
/usr/share/icons/$(basename "$icon_file")
EOF

  # build
  rpmbuild --quiet --target=${target_cpu_list[$x]} --define "__strip $arch-linux-gnu-strip" --define "_topdir $rpmdir" -bb $spec_file
           
  cp "$rpmdir/RPMS/$arch/$productname-$version_p.$arch.rpm" "$outdir/$productname.$version_p.${target_os_list[$x]}.${target_cpu_list[$x]}.rpm"
  
  if [ "$ZIP" = true ]; then
    mkdir -p "$outdir/zip"
    zip -j "$outdir/zip/$productname.$version_p.${target_os_list[$x]}.${target_cpu_list[$x]}.zip" "$outdir/$productname.$version_p.${target_os_list[$x]}.${target_cpu_list[$x]}.rpm" 
  fi

  log "$lpi" "${PUR}Linux rpm Finished${NC}"  
  
}

# -------------------------
# Build Win
# -------------------------
build_project_win64_zip() {
  local lpi="$1"
  local x=$2
  local prefix_dir_win="${$prefix_dir//\//\\}"
  local zipdir="$tmpdir/${target_cpu_list[$x]}_${target_os_list[$x]}_zip"
  
  #########################
  # Not finished yet
  #########################
  
  log "$lpi" "${PUR}Win64 zip Started${NC}"
  
  mkdir -p "$zipdir"
  log "$lpi" "mkdir $zipdir"  
  
  log "$lpi" "${PUR}win64 zip Finished${NC}"
}


# -------------------------
# Build Project
# -------------------------
build_project() {
  local lpi="$1"
  local x=0
  outdir="" 
  prjdir="$(dirname "$lpi")"

  # Create Project Temp Dir 
  tmpdir="$(mktemp -d)"
  log "$lpi" "Created project temp dir ${PUR}$tmpdir${NC}"
  
  # dist dir
  case "$OUTPUT_DIR" in
    /*) outdir="$OUTPUT_DIR" ;;
    .*) outdir=$(pwd)"${OUTPUT_DIR:1}" ;;
    ~*) outdir="$HOME""${OUTPUT_DIR:1}" ;;
    *)  err "$lpi" "Output Dir Err: $OUTPUT_DIR"
  esac
  if [ ! -d "$outdir" ]; then
    mkdir -p "$outdir"
  fi  

  for((x=0;x<${#target_os_list[@]};x++)); do
    case "${target_os_list[$x]}" in
      "linux") 
        build_project_linux_deb "$lpi" "$x"
        build_project_linux_rpm "$lpi" "$x"
        ;;
      "win64")   
        build_project_win64_zip "$lpi" "$x"
        ;;
      *)     
        err "$lpi" "${RED}Unkown OS : ${target_os_list[x]}${NC}" 
        ;;
    esac
  done
  
  # Clean Temp Dir
  if [ $KEEP = false ]; then
    rm -rf "$tmpdir"
    log "$lpi" "Cleaned project temp dir ${PUR}$tmpdir${NC}"
  else
    log "$lpi" "Kept the project temp Dir ${PUR}$tmpdir${NC}"
  fi

  
}

# -------------------------
# Process Single .lpi File
# -------------------------
process_lpi() {
  local lpi="$1"
  log "$lpi" "Processing ${PUR}'$lpi'${NC}"
  if [ ! -f "$lpi" ]; then
    err "" "File not found: ${PUR}'$lpi'${NC}"
    return 1
  fi
  
  # 读取项目参数
  load_project_config “$lpi”
  
  # Check Project Version Inforamtion
  check_project_version_information "$lpi"
  
  # 获取项目信息
  get_project_info "$lpi"
  
  # 获得构建信息
  # get_project_buildmodes_count "$lpi"
  
  # 获得构建信息列表
  get_project_buildmodes_list "$lpi"
  
  # Build Projetc
  build_project "$lpi"
  
  log "$lpi" "Finished processing ${PUR}'$lpi'${NC}"
}


# -------------------------
# Main Loop
# -------------------------
if [ "${#LPI_FILES[@]}" -eq 0 ]; then
  log "" "No LPI file specified, starting search in ${PUR}'$(pwd)'${NC}"
  # 自动查找当前目录第一个或所有 .lpi
  # mapfile -t found < <(ls -1 *.lpi 2>/dev/null || true)
  mapfile -t found < <(find "$(pwd)" -maxdepth 1 -name "*.lpi" -exec realpath {} \; 2>/dev/null || true)
  if [ "${#found[@]}" -eq 0 ]; then
    err "" "No .lpi files found in current directory. Use -f to specify."
    exit 1
  fi
  LPI_FILES=("${found[@]}")
  LPI_FILES_CNT=${#LPI_FILES[@]}
  # 输出检测到的lpi文件数量
  log "" "Get ${PUR}$LPI_FILES_CNT${NC} lpi files"
fi

get_system_info

# 循环处理每个 lpi
for f in "${LPI_FILES[@]}"; do
  process_lpi "$f" 
done

log "" "${PUR}All Finished${NC}"
