#!/bin/bash

SSH_CONFIG=$BASEDIR/configs/ssh
SSHKEY_CONFIGS=$BASEDIR/configs/sshkey

_install() {
    if [[ -z $Usage ]];then
        return 1
    fi
    if [[ ! -f $SSH_CONFIG/ssh_config ]];then
        return 1
    fi
    if [[ ! -f $SSHKEY_CONFIGS/authorized_keys.all ]];then
        return 1
    fi

    \cp -f $SSH_CONFIG/ssh_config /root/.ssh/config
    \cp -f $SSHKEY_CONFIGS/authorized_keys.all /root/.ssh/authorized_keys
    ssh-keygen -A &>> /tmp/log-debug-upload.log

    if [[ $ENVFLAG = 'offline' ]];then
        return 0
    fi

    # 通过修改sshd已经能自动下获取公钥了
    # 太慢了，交付后20分钟才能登录，先留着
    usage_key=`curl -s -L "http://softlib.service.ucloud.cn/usa/usage_key/${Usage}.pub"`
    if [[ $usage_key =~ 'ssh-rsa' ]];then
        echo "$usage_key" >> /root/.ssh/authorized_keys
    else
        PRINT_INFO "[ERROR] Usage $Usage PubKey Not Found In http://softlib.service.ucloud.cn/usa/usage_key/${Usage}.pub"
        #return 1
    fi
    # # 智能网卡uagent无arm版，先保留cloudbase uhost的key
    # if [[ $ARCH = 'aarch64' ]];then
    # 	usage_key=`curl -s -L "http://softlib.service.ucloud.cn/usa/usage_key/uhost.pub"`
    # 	if [[ $usage_key =~ 'ssh-rsa' ]];then
    #     	echo -e $usage_key >> /root/.ssh/authorized_keys
    # 	else
    #     	PRINT_ERR "[ERROR] Usage $Usage PubKey Not Found In http://softlib.service.ucloud.cn/usa/usage_key/uhost.pub"
	# 	return 1
    # 	fi
    # fi

}

_check() {
    _check="PASS"
    if [[ $ENVFLAG = 'offline' ]];then
        return 0
    fi

    grep -q "isl_sod@ucloud.cn_UcloudServers" /root/.ssh/authorized_keys
    if [ $? -ne 0 ];then
        _check="FAIL"
        PRINT_ERR "[ERROR] Special Pubkey Not Found."
    fi

#    grep -q "cloudbase" /root/.ssh/authorized_keys
#    if [ $? -ne 0 ];then
#        _check="FAIL"
#        PRINT_ERR "[ERROR] cloudbase Pubkey Not Found."
#    fi
    #检查安全公钥下发的域名和插件
    for i in 'pubkey.inventory' 'uagentbase' 'uagentdata';
    do
        ping -c1 -w5 $i.service.ucloud.cn 1>/dev/null 2>&1
        if [[ $? -ne 0 ]];then
            _check="FAIL"
            PRINT_ERR "[ERROR] ping $i.service.ucloud.cn failed."
        fi
    done
#    if [[ -z `pgrep uca_20016` ]];then
#        _check="FAIL"
#        PRINT_ERR "[ERROR] uagent plugin uca_20016 not exist."
#    fi

}
