#!/bin/bash

para="$1"

case ${para} in
    pre)
        cd /userdata
        rm -rf /userdata/*
	    sync

        [ ! -d /userdata/upgrade ] && mkdir -p /userdata/upgrade
		[ ! -d /userdata/recovery ] && mkdir -p /userdata/recovery
		[ ! -d /userdata/lost+found ] && mkdir -p /userdata/lost+found
		[ ! -f /userdata/ispeaker.log ] && touch /userdata/ispeaker.log
		[ ! -f /userdata/tmp_state.conf ] && touch /userdata/tmp_state.conf
        cat << END > /userdata/tmp_state.conf
[intercom]
onekey_state=idle
END
        sync
    ;;
    *)
        sync
        [ ! -f ${para} ] && exit 1
        model="`/etc/scripts/getmodel.sh`"
        [ -z ${model} ] && exit 1
        /usr/bin/rk_parser ${para} ${model}
        recode_check="$?"
        if [ "foo${recode_check}" != "foo0" ];then
            rm -rf ${para}
            sync
            exit 1
        fi
        sync

        reset_default="`sysconf /etc/speaker.conf get upgrade reset_default`"
        updatetime="`sysconf /etc/speaker.conf get upgrade date`"

        if [ ! -f /userdata/updatetime.txt ];then
            touch /userdata/updatetime.txt
            cat << END > /userdata/updatetime.txt
[upgrade]
date=2019-12-02
END
        fi

        sysconf /userdata/updatetime.txt set upgrade date ${updatetime}

        if [ "foo${reset_default}" = "foono" ];then
            rm -rf /oem/.upgrade
            #updateEngine --image_url=${para} --misc=update --savepath=${para}  --reboot
            tar -zxvf ${para} -C /
            recode="$?"
            if [ "${recode}" = 255 ];then
                touch /oem/.upgrade
                rm -rf ${para}
                sync
                exit 1
            fi
        else
            rm -rf /oem/.userdata
            # updateEngine --image_url=${para} --misc=update --savepath=${para}  --reboot
            tar -zxvf ${para} -C /
            recode="$?"
            if [ "${recode}" = 255 ];then
                touch /oem/.userdata
                rm -rf ${para}
                sync
                exit 1
            fi
        fi
        /usr/sbin/reboot
esac

sync

exit 0