#
# 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 [ $# -ne 2 ]; then
    echo "请提供应用名称和版本作为参数"
    exit 1
fi
architecture=$(arch)
ID=$1
base_dir="/opt/kaiming/layers/stable/${architecture}/app/${ID}/binary"
MAX_VERSION=""
for dir in "${MATCHING_DIRS[@]}"; do
    if [ -d "$dir" ]; then
        VERSION_PART=$(basename "$dir")
        if [ -z "$MAX_VERSION" ] || \
           [[ $(printf "%s\n%s" "$VERSION_PART" "$MAX_VERSION" | sort -V | tail -n1) == "$VERSION_PART" ]]; then
            MAX_VERSION="$VERSION_PART"
        fi
    fi
done

if [ "$MAX_VERSION" = "" ]; then
    echo "未安装该应用"
    exit 1;
fi

if [ $MAX_VERSION -eq $2 ]; then
    echo "已安装该版本"
    exit 1;
fi

sudo kaiming install  -y $1/$2
if [ $? -ne 0 ]; then
    echo "安装失败:$1/$2"
    exit 1
fi

if [ -d "${base_dir}/$2" ]; then
    if [-d "${base_dir}/${MAX_VERSION}"]; then
        echo "${ID}删除旧版本失败" 
        exit 1
    else
        echo "${ID}已删除旧版本，安装新版本$2"
    fi
else
    echo "安装失败:$1/$2" 
    exit 1
fi