#!/bin/bash
if [[ $# -ne 3 && $# -ne 0 ]]; then
    echo -e "\033[32m Usage: ./init.sh IDC Usage SecUsage \033[0m"
    exit 1
fi

logger() {
    echo [$1] $2
    echo $(date +"%Y-%m-%d %H:%M:%S ") [$1] $2 >>/tmp/$hostname.log
    if [[ ($1 != 'debug') && (-n $u_uuid) ]]; then
        curl http://vm-mgr.service.ucloud.cn/vm-mgr/v1/vm/receive -X POST -H 'Content-Type:application/json' -d "{\"Action\":\"init\",\"UID\":\"$u_uuid\",\"SubStatus\":\"$1\",\"Info\":\"$2\"}"
    fi
    if [[ $1 = 'success' ]]; then
        exit 0
    elif [[ $1 = 'failed' ]]; then
        exit 1
    fi
}

dmi=$(dmidecode -t1)

if [[ ! $dmi =~ 'Product Name: KVM' ]]; then
    echo 'This is not a vm!'
    exit 1
fi

u_uuid=$(echo "$dmi" | grep UUID | awk '{ print $2 }' | tr 'A-Z' 'a-z')

#判断是否已经初始化
grep 'UCLOUD_INIT=1' /ucloud/exports.ini
if [[ $? -eq 0 ]]; then
    logger 'success' 'already inited'
    exit 0
fi

#初始化参数
mkdir /ucloud
cat >/ucloud/init_info <<EOF
IDC=$1
REGION=$1
Usage=$2
SecUsage=$3
EOF

#echo "nameserver 172.18.39.101" > /etc/resolv.conf

rm -f /root/ucloud-basic-init.sh
wget http://softlib.service.ucloud.cn/usa/ucloud-basic-init/ucloud-basic-init.sh


if cat /etc/redhat-release | grep -q "Rocky Linux release 9.4 (Blue Onyx)"; then
    # 优先走ipv4
    echo "precedence ::ffff:0:0/96  100" > /etc/gai.conf

    # 清理原生镜像的yum源
    rm -rf /etc/yum.repos.d/*

    # Rocky9没有上线前，现在测试环境使用。 初始化地址和分支不一样，正式上线之后可以移除这段逻辑！
    sed -i 's#softlib.service.ucloud.cn/usa/ucloud-basic-init#10.72.161.114#g' ucloud-basic-init.sh
fi

bash ucloud-basic-init.sh install
bash ucloud-basic-init.sh check

grep 'UCLOUD_INIT=1' /ucloud/exports.ini
if [[ $? -eq 0 ]]; then
    logger 'success' 'init success'
    exit 0
else
    logger 'failed' 'init failed'
    exit 1
fi
