#!/bin/sh

. /etc/PG.conf

DBTYPE=$1

if [ "`uname -m`" = "aarch64" ]; then
	CURL="/usr/pabin/pacu -s -k"
else
	CURL="`which curl` -s -k"
fi

data_dir="${DATAPATH}/qtde_pro"
FLOWEYE="/usr/ramdisk/bin/floweye"

if [ "${DBTYPE}" = "1" ]; then
  channel_code="tde_QAX-TINTM-B_QAX-TINTM-B"
  channel_key="nzxdichw8b7683p7"
  malc_file="PanabitMALC_qianxin.db"
  DBID=1
else
  DBID=4
  channel_code="tde_Panabit-promax_Panabit-promax"
  channel_key="TGi2DkKm0whH36Gs"
  malc_file="PanabitMALC_qianxin2.db"
fi


json_str_get()
{
	local str="$1"
	local key="$2"

	# " } ȷŻɿ
	# {  ,
	echo "${str}" | sed 's/[}"]//g' | sed 's/{/,/g' | awk -F"," -v key=${key} \
	'{
		for(i = 1 ; i <= NF; i++) {
			split($i, obj, ":");

			if(obj[1] == key)
				print obj[2];
		}
	}'
}

# Ŀ¼
mkdir -p ${data_dir}
rm -rf ${data_dir}/*

# 1.ȡ鱨汾
echo "Step 1/6: ȡ汾..."
upgrade_response=`${CURL} -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "customer": {
      "asset_id": {
        "oid": 2643739354052240400,
        "id": 100101
      },
      "client": ""
    },
    "channel_code": "'"$channel_code"'",
    "version": "0.0.0.0"
  }' \
  https://darwin.qianxin.com/PacketV2/GetUpgradePacket
`
version=`json_str_get "${upgrade_response}" "ver"`
[ -z "$version" ] && { echo "ȡ汾ʧ"; exit 1; }

# 2.ȡļԪ
echo "Step 2/6: ȡļԪϢ..."
meta_response=`${CURL} -s -k -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "key": {
      "channel_id": {
        "product_id": "tde",
        "id": "'"$channel_code"'"
      },
      "ver": "'"$version"'"
    }
  }' \
  https://darwin.qianxin.com/PacketV2/GetPacketMeta
`

file_id=`json_str_get "${meta_response}" "file_id"`
[ -z "$file_id" ] && { echo "ȡļIDʧ"; exit 1; }

# 3.ȡصַ
echo "Step 3/6: ȡصַ..."
storage_response=`${CURL} -s -k -X POST \
  -H "Content-Type: application/json" \
  https://darwin.qianxin.com/FileV2/GetFileStorageAddr
`

download_host=`echo "${storage_response}" | cut -d"," -f1 | cut -d":" -f2- | sed 's/"//g'`
[ -z "$download_host" ] && { echo "ȡصַʧ"; exit 1; }

# 4.ؼļ
echo "Step 4/6: ؼļ..."
download_url="$download_host/$file_id"
${CURL} -o "${data_dir}/enc.tar.gz" "$download_url"

# 5.ܲѹļ
echo "Step 5/6: ܲѹ..."
openssl enc -aes-256-cbc -d -salt -md sha256 \
  -k "$channel_key" \
  -in "${data_dir}/enc.tar.gz" \
  -out "${data_dir}/dec.tar.gz"

tar -zxf "${data_dir}/dec.tar.gz" -C "$data_dir"
rm -f "${data_dir}/dec.tar.gz"
[ ! -f ${data_dir}/compromise.db ] && exit 1;

# 6. ϵͳ
echo "Step 6/6: ϵͳ..."
mkdir -p ${DATAPATH}/pamalc
mv ${data_dir}/compromise.db ${DATAPATH}/pamalc/${malc_file}
${FLOWEYE} malc load db=${DBID} file=${DATAPATH}/pamalc/${malc_file}
rm -rf ${data_dir}
