#!/bin/sh

locale_echo()
{
    lang_l=`echo $LANG|awk -F"." '{print $1}'`
    if [ x"$lang_l" == x"" ];then
        echo $1
        return
    fi
    lang_f="/usr/share/libkylin-activation/locale/"$lang_l
    if [ ! -f $lang_f ];then
        echo $1
        return
    fi

    est=`grep "^$1==" $lang_f|head -1|awk -F"==" '{print $2}'`
    if [ x"$est" != x"" ];then
        echo "$est"
	else
        echo $1
    fi

}

if [ $# -gt 0 ];then
    locale_echo "Usage: kylin_activation_recycle"
    locale_echo "This program is used to activation recycle!"
    exit 0
fi


user=$(whoami)

if [ "$user" != "root" ]; then
	locale_echo "Please use sudo or switch to the root user to execute the program"
	exit 1;
fi


# 0,未激活；1，kms激活；2，扫码激活；3，ukey激活；4，场地授权；5，密钥激活；6，其他方式
get_activate_style()
{
	isactivated=`LANG=C kylin_activation_check|grep "System is activated."`
	##未激活状态
	if [ x"$isactivated" == x"" ];then
		return 0
	fi	

	##场地授权
	isplace=`grep "METHOD:place" /etc/LICENSE`
	if [ x"$isplace" != x"" ];then
        return 4
    fi

	conf=/usr/share/libkylin-activation/activation_conf.ini
	if ! [ -f $conf ];then
		return 6		
	fi
	
	flag=`grep activate_style $conf|awk -F"=" '{print $NF}'|awk '{print $1}'|head -1`

	if [ x"$flag" == x"" ];then
		return 6
	else
		return $flag
	fi
	

}

show_qrcode() {
	kylin_serial> /dev/null || exit 1
    SERIAL_CODE=$(kylin_serial)
	kylin_gen_register  > /dev/null || exit 1
    REGISTER_NO=`CODE_NO_HYPHEN=y kylin_gen_register $SERIAL_CODE`

	lic_serial=$(/usr/bin/kylin_productinfo|grep ^bak_lic_serial=|awk -F"=" '{print $2}')

	QR_CODE_STR="https://wx.kylinos.cn/qywx/distro/activate?f=${SERIAL_CODE}&z=${REGISTER_NO}&p=${lic_serial}"

    if [ "$QRCODE_TYPE" == "" ]; then
        QRCODE_TYPE="ANSI"
    fi

    clear
    qrencode -t "$QRCODE_TYPE" -m 2 "${QR_CODE_STR}" 2> /dev/null && \
	locale_echo "Please scan the QR code, deactivate on the platform, and then press Enter to confirm cancellation" && \
                #sleep 2 && \
    #locale_echo "Please press Enter to continue..." && \
    read TMP

	rm -f /etc/.kyhwid /etc/.kyactivation
	
	if [ -f /etc/.kyhwid ] || [ -f /etc/.kyactivation ];then
		exit 1
	else
		locale_echo "Deactivation Sucess"
	fi
	
	exit 0

}


main()
{
	get_activate_style
	flag=$?

	##未激活
	if [ x"$flag" == x"0" ];then
		locale_echo "The system is not activated!"
		exit 0
	fi

	##给场地激活
	if [ x"$flag" == x"4" ];then
        locale_echo "Place activation do not support activation cancel!"
        exit 0
    fi

	##kms激活
	if [ x"$flag" == x"1" ];then
        /usr/bin/kylin_kms -r
        exit 0
    fi

	##其他激活方式

    show_qrcode


}

main
