#
# Copyright (c) KylinSoft  Co., Ltd. 2024. All rights reserved.
#
# kaiming is licensed under the GPL v2.0+.
#
# See the LICENSE file for more details.
#

#!/bin/bash
if [ $# -eq 0 ]; then
    echo "请提供应用架构作为参数"
    exit 1
fi
# 初始化一个数组用于存储 id/name/version/module/channel 信息
install_info=()
architecture=$1
# 使用 kaiming search "" 检索信息并提取字段
result=$(sudo kaiming search --arch="$architecture" ""| awk 'NR > 2')
while IFS= read -r line; do
    # 提取第一个字段作为 id
    id=$(echo "$line" | awk '{print $1}')
    if [[ -z "$id" ]]; then
        continue
    fi

    # 提取剩余部分，去掉 id 后的所有内容
    remaining=$(echo "$line" | sed -E "s/^$id //")

    # 初始化变量
    version=""
    channel=""
    module=""
    i=0

    # 将 remaining 按空格拆分成数组
    read -r -a temp_fields <<< "$remaining"
    while [[ -n "${temp_fields[i]}" ]]; do
        if [[ "${temp_fields[i]:0:1}" =~ [0-9] ]]; then
            version="${temp_fields[i]}"
            channel="${temp_fields[i+1]}"
            module="${temp_fields[i+4]}"
            break
        else
            ((i++))
        fi
    done

    if [[ -n "$id" && -n "$module" && -n "$version" ]]; then
        install_info+=("$id/$module/$version")
    fi
done <<< "$result"
# printf "%s\n" "${install_info[@]}"
IFS=$'\n' sorted=($(printf "%s\n" "${install_info[@]}" | sort))
unset IFS
sorted_refs=($(sudo ostree remote --repo=/opt/kaiming/repo refs kaiming-repo | \
             awk -F '/' '$2=="'"$architecture"'" {print $(NF-2)"/"$(NF-1)"/"$NF}' | sort))

#echo "${sorted_refs[@]}"
for ((i = 0; i < ${#sorted[@]}; i++)); do
    if [[ "${sorted[i]}" == "${sorted_refs[i]}" ]]; then
	    echo "found:${sorted[i]}"
    else
        echo " search缺少${architecture}架构的：${sorted[i]}, 或者remote多余${architecture}架构的: ${sorted_refs[i]})"
        exit 1
    fi
done
