#!/bin/bash

ACTION=$1
ENVFLAG=$2
PANGU=$3
CHANNEL=$4

Usage() {
    echo -e "\033[31mUsage:\t
    bash $0 ACTION ENVFLAG PANGU CHANNEL
    ACTION: 初始化 install 交付检查 check
    ENVFLAG: pro 盘古线上环境 pre 盘古测试环境 offline 离线环境
    PANGU: 这个参数如果是 PANGU 则向盘古传递执行状态和日志
    CHANNEL: 判断初始化机器来源,对应 sod-pangu 的三种选项: install,reinstall,upan 只有177脚本用到 CHANNEL
	1. bash $0 install
	2. bash $0 check
	# bash ucloud-basic-init.sh install pro sodpangu install
	Debug: cat /tmp/os_init/init.log
	 \033[0m"
}

INIT_TMP_DIR="/tmp/os_init"
INIT_LOG="$INIT_TMP_DIR/init.log"
BASEDIR="$INIT_TMP_DIR/ucloud-basic-init"
# 代码版本，无特殊意义，想起来就同时改一下，与太久的脚本区分
INIT_VERSION="v1.7"

pid_file=/tmp/osinit.pid
osinit_pid_make() {
    if [ -e $pid_file ]; then
        pid_check=$(pgrep -F $pid_file)
        if [ -z "$pid_check" ]; then
            /usr/bin/rm -f $pid_file
        else
            echo "PID $pid_check is still running or pgrep check errored. Exiting."
            exit 1
        fi
    fi
    # echo "Creating .pid file $pid_file"
    echo $$ > $pid_file
}
osinit_pid_make

trap osinit_pid_delete EXIT
osinit_pid_delete() {
    [[ -e $pid_file ]] && { echo delete pid file ;cat $pid_file ;ps ajxf; } >> /tmp/log-debug-upload.log  && /usr/bin/rm -f $pid_file
}

echo -e >> /tmp/log-debug-upload.log INIT_VERSION: $INIT_VERSION

if [[ $ENVFLAG = pro ]];then
    if ping -c3 osinstall.service.ucloud.cn &> /dev/null ;then
        UCLOUD_OSINIT_SERVICE=osinstall.service.ucloud.cn
    else
        UCLOUD_OSINIT_SERVICE="10.81.41.34"
    fi
elif [[ $ENVFLAG = gray ]];then
    UCLOUD_OSINIT_SERVICE="10.81.41.34:8125"
elif [[ $ENVFLAG = pre ]];then
    UCLOUD_OSINIT_SERVICE="192.168.168.154:8092"
elif [[ $ENVFLAG = offline ]];then
    UCLOUD_OSINIT_SERVICE="127.0.0.1"
else
    UCLOUD_OSINIT_SERVICE="10.81.41.34"
fi

PREPARE(){
    sed -i '/softlib.service.ucloud.cn/d' /etc/hosts
    sed -i '/yum.service.ucloud.cn/d' /etc/hosts
#    HOSTIP=`ping -c1 -w1 192.168.168.106 -B|sed -n 's/.*from \([0-9\.]*\) .*/\1/p'`
    JP='192.168.168.106'
    HOSTIP=`ip -o r get $JP|sed -n 's/.*src \([0-9.]*\) .*/\1/p'`
    # for 内网控制台
    if [[ `echo $HOSTIP | grep -c '^100.'` -eq 1  ]];then
        local softlib='172.18.181.49'
        echo "$softlib softlib.service.ucloud.cn" >> /etc/hosts
        echo "$softlib yum.service.ucloud.cn" >> /etc/hosts
    elif ! grep -q '^nameserver' /etc/resolv.conf ;then
        source /ucloud/conf.ini
        if [[ -n $UCLOUD_KS_IP ]];then
            echo "nameserver $UCLOUD_KS_IP" > /etc/resolv.conf
        else
            echo "nameserver 10.64.50.101" > /etc/resolv.conf
        fi
    fi
}

wget_script(){
    REMOTE_URL="http://softlib.service.ucloud.cn/usa/ucloud-basic-init/ucloud-basic-init.tgz"
    rm -rf $INIT_TMP_DIR
    mkdir $INIT_TMP_DIR
    touch $INIT_LOG
    wget -qN $REMOTE_URL -O $INIT_TMP_DIR/ucloud-basic-init.tgz
    if [ $? -ne 0 ]; then
	    echo -e "\033[31m[ERROR] Package Download Failed.\033[0m"
        exit 1
    fi
    tar xf $INIT_TMP_DIR/ucloud-basic-init.tgz -C $INIT_TMP_DIR
    if [ $? -ne 0 ]; then
	    echo -e "\033[31m[ERROR] Package Unzip Failed.\033[0m"
        exit 1
    fi
}


if [[ $ACTION = install ]];then
    if [[ -f "/ucloud/exports.ini" ]];then
        if  [[ -z $PANGU ]] && [[ `grep -c "UCLOUD_INIT=1" /ucloud/exports.ini` -ne 0 ]];then
            echo "System Init Already Done! "
            echo "If you want do it again, Delete the line 'UCLOUD_INIT=' in /ucloud/exports.ini"
            exit 1
        else
            sed -i '/UCLOUD_INIT/d' /ucloud/exports.ini
        fi
    fi

    PREPARE

    begin_time=$(date -u +"%Y-%m-%d %H:%M:%S")
    echo -e "\033[32m[INIT BEGIN] 开始时间: $begin_time UTC\033[0m"

    wget_script
elif [[ $ACTION = check ]];then
    # 保存install日志，避免check环节被删除
    \cp -f $INIT_LOG /tmp/INIT_LOG    
    wget_script
    \cp -f /tmp/INIT_LOG $INIT_LOG   
    echo -e "\033[32m[CHECK BEGIN] \033[0m"
else
    echo -e "\033[31m[ERROR] Argument Input Failed, As Follows: \033[0m"
    Usage
    exit 1
fi

# Load libs.sh
. $BASEDIR/lib.sh

if [[ -n $PANGU ]];then
    # Run
	if [[ $(grep -c 'Tip' /tmp/os_init/init.log) -eq 0 ]];then
            PRINT "<font color='green'>Tips: Step1: 系统初始化, Step2: 交付前检测</font>"
            PRINT "<font color='green'> IP: $(hostname -I)</font>"
            PRINT "<font color='green'> tar_md5: $(curl -fsSL $REMOTE_URL.md5) </font>"
            PRINT "--------------------------------------------------------"
	fi
	# Get Running Environment Info
    if ! Get_Env_Info ;then
        PRINT_ERR "[ERROR] Init Environment Check Fail."
		if [[ -z $SN ]];then
            # dmidecode -s system-serial-number 可能出现一种情况："<BAD INDEX>"
            SN=`dmidecode -s system-serial-number |grep -v ^#  | sed s/[[:space:]]//g`
            [[ $SN == "<BADINDEX>" ]] && SN=$(grep 'UCLOUD_SN=' /ucloud/exports.ini |tail -1 | awk -F '=' '{print $NF}')
      	fi
      	data=$( cat <<EOF
{
    "Action": "updateDeployServer",
    "Token": "02135cd55baa4d91987aac0b93af7d14",
    "DataSet": [
        {
            "Info": "获取环境变量失败，初始化/交付检测失败",
            "SN": "${SN}",
            "SubStatus": "init_checkfail",
            "Action": "init"
        }
    ]
}
EOF
      	)
        curl http://${UCLOUD_OSINIT_SERVICE}/IdcDeploy/execTask/ -d data &>> /tmp/log-debug-upload.log
        UPLOAD_LOG FAIL
        echo -e >> /tmp/log-debug-upload.log '\n' `date +%F_%T` ucloud-basic-init.sh post updateDeployServer_init_init_checkfail_end $UCLOUD_OSINIT_SERVICE env_fail $PANGU '\n'
        exit 1
    fi

	if [[ $ACTION = install ]];then
		# Upload init_initing To Frontend
		substatus=init_initing
	elif [[ $ACTION = check ]];then
		# Upload init_check To Frontend
		substatus=away_checking
	fi
	data=$( cat <<EOF
{
    "Action": "updateDeployServer",
    "Token": "02135cd55baa4d91987aac0b93af7d14",
    "DataSet": [
        {
            "Info": "开始执行请等待",
            "SN": "${SN}",
            "SubStatus": "${substatus}",
            "Action": "init"
        }
    ]
}
EOF
	)
	curl http://${UCLOUD_OSINIT_SERVICE}/IdcDeploy/execTask/ -d "$data" &>> /tmp/log-debug-upload.log

    echo -e >> /tmp/log-debug-upload.log '\n' `date +%F_%T` ucloud-basic-init.sh post updateDeployServer_init_init_initing_end $UCLOUD_OSINIT_SERVICE $ACTION $PANGU '\n'
else
	# Get Running Environment Info
    if ! Get_Env_Info ;then
        PRINT_ERR "[ERROR] Init Environment Check Fail."
    fi
fi

cd $INIT_TMP_DIR/ucloud-basic-init && source ./start.sh

