#!/bin/bash




#############################################################
# ===== Log =====
# log.info xxx
# log.warn xxx
# log.info xxx
# log.debug xxx
# 带颜色的echo
function log.color_output() {
    local color=$1
    shift 1

    echo >&2 -e "\033[${color}m$@\033[0m"
    return 0
}

# Log is named without prefix "utils." for convenience
# Usage: log.log <level> ...content
function log.log() {
    if [[ $# < 2 ]]; then
        return -1
    fi

    local level=$1
    shift 1

    case $level in
    error) log.color_output "0;31" "[ERROR] $@" ;;
    warn) log.color_output "1;33" "[WARN] $@" ;;
    info) log.color_output "1;37" "[INFO] $@" ;;
    debug) log.color_output "1;30" "[DEBUG] $@" ;;
    esac

    return 0
}

function log.error() { log.log "error" "$@"; }
function log.warn() { log.log "warn" $@; }
function log.info() { log.log "info" $@; }
function log.debug() { log.log "debug" $@; }


# 发送通知
function notify-send() {


    # Detect user using the display
    local user=$(who | awk '{print $1}' | head -n 1)

    # Detect uid of the user
    local uid=$(id -u $user)
    log.debug "User is $user and the uid of it is $uid"
    sudo -u $user  DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/${uid}/bus notify-send $@
}


# 检测网络链接畅通
function network-check()
{
    # 超时时间
    local timeout=15

    # 目标网站
    local target=www.baidu.com

    # 获取响应状态码
    local ret_code=`curl -I -s --connect-timeout ${timeout} ${target} -w %{http_code} | tail -n1`

    if [ "x$ret_code" = "x200" ] ; then
        # 网络畅通
        return 0
    else
        # 网络不畅通
        return 1
    fi
}
###############################################################

if [ "$(id -u)" != "0" ]; then
log.error "Nope we need root to run"
exit -1
fi

network-check
if [ $? -ne 0 ] ; then
    log.error "NETWORK_FAIL"
    exit -1
fi

# The code above is modified from https://blog.csdn.net/yaxuan88521/article/details/120516298




if command -v aptss  ;then
APT_COMMAND=aptss
/usr/bin/apt update
log.info "Using aptss to operate the upgrade process since we detect it."
elif [ -e /usr/bin/apt ];then
APT_COMMAND=/usr/bin/apt
log.info "Using apt to operate the upgrade process."
else
log.error "Nope we support debian only now"
exit -1
fi
${APT_COMMAND} clean
${APT_COMMAND} update

updatetext=`${APT_COMMAND} update 2>&1`

until [ "`echo $updatetext | grep E: `" = "" ];do
log.info "UPDATE_ERROR_AND_WAIT_15_SEC"
sleep 15
updatetext=`${APT_COMMAND} update 2>&1`



done


# 获取可升级包的数量
update_app_number=$(env LANGUAGE=en_US ${APT_COMMAND} list --upgradable 2>/dev/null | grep -c upgradable)

if [ "$update_app_number" -le 0 ] ; then
    exit 0
fi

# 获取用户选择的要更新的应用
PKG_LIST="$(env LANGUAGE=en_US ${APT_COMMAND} list --upgradable  | awk NR\>1)"
# 指定分隔符为 \n
IFS_OLD="$IFS"
IFS=$'\n'

for line in $PKG_LIST ; do
    PKG_NAME=$(echo $line | awk -F ' ' '{print $1}')
    PKG_NEW_VER=$(echo $line | awk -F ' ' '{print $2}')
    PKG_CUR_VER=$(echo $line | awk -F ' ' '{print $3}')

#    dpkg --compare-versions $PKG_NEW_VER le $PKG_CUR_VER

#    if [ $? -eq 0 ] ; then
#        let update_app_number=$update_app_number-1
#        continue
#    fi

    ## 检测是否是 hold 状态
    PKG_STA=$(dpkg-query -W -f='${db:Status-Want}' $PKG_NAME)
    if [ "$PKG_STA" = "hold" ] ; then
        let update_app_number=$update_app_number-1
    fi
done

# 还原分隔符
IFS="$IFS_OLD"
if [ $update_app_number -le 0 ] ; then
	log.info "No package need to upgrade after ignoring those holded ones. exit"
    exit 0
fi


## 如果都是hold或者版本一致的那就直接退出，否则把剩余的给提醒了


user=$(who | awk '{print $1}' | head -n 1)

	log.info "ACE Bookworm环境中有 $update_app_number 个软件包可升级，正在自动升级"
notify-send -a amber-ce-bookworm "ACE兼容环境" "ACE环境中有${update_app_number}个软件包可升级，执行自动升级..."

${APT_COMMAND} clean
${APT_COMMAND} full-upgrade -y
${APT_COMMAND} clean
notify-send -a amber-ce-bookworm "ACE兼容环境" "自动升级结束"
