#!/bin/sh
folder_path="/tmp/config_root"
pattern="|>>|"
myFile=/tmp/replace.info
myFile_gz=/tmp/config.tar.gz

help() {
    cat <<_HELP_
ipk install api wrapper

Usage:  $0  or $0 -m SN "SN length must be 12 "

Example:
    $0
    or
    $0 -m 21881P000000
_HELP_
}

case "$1" in
        -m) MAST_SN="$2" 
            if [ ${#MAST_SN} -ne 12 ];then
                help
                exit 1
            fi            
            ;;  
	-*) help; exit 1;;
        *);;
esac

do_change()
{
     search_text="$1"
     replace_text="$2"
     find "$folder_path" -type f -exec sed -i "s/$search_text/\[$replace_text\]/g" {} \;
     return 0
}

gc_exec()
{
    gc_flag="$1"
    rm -rf "$folder_path"
    if [ -f "$myFile_gz" ]; then
     rm "$myFile_gz"*
     echo "gz rm"
    fi
    if [ -f "$myFile" ]; then
       rm "$myFile"
    fi
    return "$gc_flag"
}


gc_exec 0
mkdir "$folder_path"/app/ -p
cp /app/config "$folder_path"/app/ -R
find "$folder_path" -type f ! -name "*.json" -exec rm -f {} \;

cp /app/node "$folder_path"/app/ -R
cp /app/script "$folder_path"/app/ -R

mkdir "$folder_path"/etc
cp /etc/config "$folder_path"/etc -R

#PRO=$(/lib/dyiot/bin/factory get | grep "PRODUCT=" |awk -F '-' '{print $NF}')
#echo 'product is '$PRO
#if [ "$PRO" == "V3" ]; then
#    frp="$folder_path"/etc/frpc.ini
#    echo -e "[common]\nserver_addr = frps.lnxall.com\nserver_port = 7000\nlog_file = /tmp/frpc.log\nlog_level = info\nlog_max_days = 2\n\
#privilege_token = dywlfrp123\nadmin_addr = 127.0.0.1\nadmin_port = 7400\nadmin_user = admin\n\
#admin_pwd = dyiot123\nuser = [GW_SN]\n[ssh_[GW_SN]]\ntype = tcp\nlocal_ip = 127.0.0.1\nlocal_port = 22\nremote_port = 0\nuse_compression = true\n\n\
#[ssh_[GW_SN]_web]\ntype = tcp\nlocal_ip = 172.18.39.167\nlocal_port = 80\nremote_port = [EMS_WEB_PORT]\nuse_compression = true" >> $frp
#    chmod 755 $frp
#fi

cd "$folder_path"
ret=`lua /lib/dyiot/bin/remove_json_one_key.lua /app/config/uplink_channels.json client_id`
echo "$ret"

SN_BASE=$(/lib/dyiot/bin/factory get | grep -i 'SN=' | awk -F '=' '{print $2}')

    first=$(echo "$SN_BASE" | awk '{printf substr($0,1,5)}')
    second=$(echo "$SN_BASE" | awk '{printf substr($0,7)}')
    rst=$(echo "$SN_BASE" | awk '{printf substr($0,6,1)}')
    if [ "$rst" == "D" ]; then
       SN_CHANGE=$(echo "$first""E""$second")
       do_change "$SN_CHANGE" "GW_6UL_SN"
    fi
    do_change "$SN_BASE" "GW_SN"
if [ ${#MAST_SN} -eq 12 ];then
    do_change "$MAST_SN" "MS_GW_SN"
    echo "|>>|key: [MS_GW_SN]  value: 21881F000000"
fi

cd "$folder_path"
tar czf /tmp/config.tar.gz *
chmod 755 /tmp/config.tar.gz

echo "|>>|success  config file path: /tmp/config.tar.gz"
echo "|>>|The key value of replaceList.xlsx must be updated !!!"
echo "|>>|path: tools/replaceList.xlsx"

