#!/bin/sh

echo "Recovery license @#"

if [ $# -lt 2 ]; then
    echo "error: need 2 args!"
    exit -1
fi

from_path=$1
to_path=$2

actionType=${3-}

licenseAdapter() {
    if [ ! -d "${to_path}/var" ]; then
        mkdir -p "${to_path}/var"
        echo "var dir is not exit,mkdir it!"
    fi
    mount --bind "${from_path}/var" "${to_path}/var"
    chroot "${to_path}" /var/uos/.licenseadapter -live
    umount "${to_path}/var"
}

if [ "${actionType}" = "license-adapter" ]; then
    if [ -f "${from_path}/var/uos/.licenseadapter" ]; then
        licenseAdapter
    fi

    exit 0
fi

if [ ! -d "${from_path}" ]; then
    echo "error: from path is not exist!"
    exit -1
fi

if [ ! -d "${to_path}" ]; then
    mkdir -p "${to_path}"
    echo "dir is not exit,mkdir it!"
fi

cpSysLicense() {
    if [ -f "${from_path}/.sysuuid" ]; then
        cp -a "${from_path}/.sysuuid" "${to_path}"
    fi

    if [ -f "${from_path}/.appsysuuid" ]; then
        cp -a "${from_path}/.appsysuuid" "${to_path}"
    fi
}

if [ "${actionType}" = "etc-sys-license" ]; then
    cpSysLicense
    exit 0
fi

if [ -f "${from_path}/.license.key" ]; then
    cp -a "${from_path}/.license.key" "${to_path}"
fi

if [ -f "${from_path}/.license.xkey" ]; then
    cp -a "${from_path}/.license.xkey" "${to_path}"
fi

if [ -f "${from_path}/.licenseadapter" ]; then
    cp -a "${from_path}/.licenseadapter" "${to_path}"
fi

if [ -f "${from_path}/.manufacturer.key" ]; then
    cp -a "${from_path}/.manufacturer.key" "${to_path}"
fi

if [ -e "${from_path}/os-license" ]; then
    cp -a "${from_path}/os-license" "${to_path}"
fi

if [ -e "${from_path}/../lib/uos-license/.license.json" ]; then
    mkdir -p "${to_path}/../lib/uos-license"
    cp -a "${from_path}/../lib/uos-license/.license.json" "${to_path}/../lib/uos-license"
fi

if [ -f "${from_path}/../lib/deepin/developer-mode/signature" ]; then
    destDir="${to_path}/../lib/deepin/developer-mode/"
    mkdir -p "${destDir}"
    cp -a "${from_path}/../lib/deepin/developer-mode/signature" "${destDir}"
    if [ $? -ne 0 ]; then
        chattr -i "${destDir}/signature"
        cp -a "${from_path}/../lib/deepin/developer-mode/signature" "${destDir}"
        chattr +i "${destDir}/signature"
    fi
fi

if [ -e "${from_path}/.trialinfo.key" ]; then
    cp -a "${from_path}/.trialinfo.key" "${to_path}"
fi

if [ -e "${from_path}/.verify.key" ]; then
    cp -a "${from_path}/.verify.key" "${to_path}"
fi

if [ -e "${from_path}/.applicense" ]; then
    cp -a "${from_path}/.applicense" "${to_path}"
fi

echo "Recovery livense end!"
