#!/bin/bash

traverse_directory() {
  local directory="$1"
  local setting_path="$2"
  local repository_id="$3"
  local repository_url="$4"

  for file in "$directory"/*; do
    if [[ -f "$file" && "$file" == *.jar ]]; then
      IFS='/'
      read -ra parts <<< "$file"

      length=${#parts[@]}
      file_Name_withOut_suffix="${file%????}"
      if [ -z "$setting_path" ]; then
        mvn deploy:deploy-file -Dfile="$file" -DgroupId=com.manatee.manatee-lowcode -DartifactId="${parts[length-3]}" -Dversion="${parts[length-2]}" -Dpackaging=jar -DpomFile="${file_Name_withOut_suffix}.pom" -Durl="${repository_url}" -DrepositoryId="${repository_id}" -X
      else 
        mvn deploy:deploy-file -s "$setting_path" -Dfile="$file" -DgroupId=com.manatee.manatee-lowcode -DartifactId="${parts[length-3]}" -Dversion="${parts[length-2]}" -DpomFile="${file_Name_withOut_suffix}.pom" -Dpackaging=jar -Durl="${repository_url}" -DrepositoryId="${repository_id}"
      fi
    
    elif [[ -d "$file" ]]; then
      traverse_directory "$file" "$setting_path" "$repository_id" "$repository_url"
    fi
  done
}


traverse_pom_directory() {
  local directory="$1"
  local setting_path="$2"
  local repository_id="$3"


  for file in "$directory"/*; do
    if [[ -f "$file" && "$file" == *.pom ]]; then
      IFS='/'
      read -ra parts <<< "$file"
      length=${#parts[@]}

      if [ -z "$setting_path" ]; then
        mvn deploy:deploy-file -Dfile="$file" -DgroupId=com.manatee.lowcode -DartifactId="${parts[length-3]}" -Dversion="${parts[length-2]}" -Dpackaging=pom -Durl="${repository_url}" -DrepositoryId="${repository_id}"
      else 
        mvn deploy:deploy-file -s "$setting_path" -Dfile="$file" -DgroupId=com.manatee.lowcode -DartifactId="${parts[length-3]}" -Dversion="${parts[length-2]}" -Dpackaging=pom -Durl="${repository_url}" -DrepositoryId="${repository_id}"
      fi
    elif [[ -d "$file" ]]; then
      traverse_pom_directory "$file" "$setting_path" "$repository_id" "$repository_url"
    fi
  done
}

current_directory=$(pwd)/manatee-lowcode

current_pom_directory=$(pwd)/lowcode

echo "请输入 setting 文件目录（可回车键跳过使用maven默认配置文件）："
read setting_path;

echo "请输入serverId ，要求和setting配置文件中的server标签id一致："
read repository_id;

echo "请输入仓库地址："
read repository_url;

traverse_directory "$current_directory" "$setting_path" "$repository_id" "$repository_url"
traverse_pom_directory "$current_pom_directory" "$setting_path" "$repository_id" "$repository_url"