#!/bin/sh

USAGE="Add a storage node to the management node 

  Usage: $(basename $0) -n <host-name> 

  Parameters:
    -n  storage node host name
    -h  Print this message
"

agent_port=17514

usage() {
    echo >&2
    echo "${USAGE}" >&2
    exit 1
}

error() {
    if [ "$1" = "--usage" ]; then
        shift
        echo "ERROR: $*" >&2
        echo >&2
        echo "${USAGE}" >&2
    else
        echo "ERROR: $*" >&2
    fi
    exit 1
}


parse_opt() {
    while getopts h:n:p: opt; do
        case $opt in
            n)
                HOST_NAME="$OPTARG"
                ;;
	        p)
		        agent_port=$OPTARG
		        ;;
            h|*)
                usage
                ;;
        esac
    done

    [ -z "${HOST_NAME}" ] && error --usage "Host name should be specified"
}


resolve_host() {
    ent=$(getent hosts $1)
    [ $? -ne 0 ] && {
        echo $1 | grep -qE '^([0-9]{1,3}\.){3}([0-9]{1,3})$' && {
            echo "Unable to resolve hostname by address $1"
            usage
        }
        echo "Unable to resolve address by hostname $1"
        usage
    }
    hostname=$(echo $ent | sed -ne 's/^.\+[\t ]\+\(.\+\)$/\1/p')
    return $?
}


get_node_id() {
    res=$(curl -s --get $1/api/v1/node_id/)
    if [ $? -ne 0 ]; then 
    	echo "Error executing curl -s --get $1/api/v1/node_id/"
	    exit 1
    fi
    node_id=$(echo $res | sed -ne 's/^.*\"node_id\": *\"\([0-9a-z]\+\)\".*$/\1/p')
}

get_host_id() {
    res=$(curl -s --get $1/api/v1/host_id/)
    if [ $? -ne 0 ]; then 
        echo "Error executing curl -s --get $1/api/v1/host_id/"
        exit 1
    fi
    host_id=$(echo $res | sed -ne 's/^.*\"host_id\": *\"\([0-9a-z]\+\)\".*$/\1/p')
}

register_node() {
    count=$(psql -tAc "select count(*) from nodes where id = '$node_id'" 2>/dev/null )
    if [ $? -ne 0 ]; then 
        echo "Database error!"
        exit 2
    fi
   
    [ "$count" != "0" ] && {
        echo "Node $hostname has already been registered"
        exit 0
    }
    host_ip=$(echo $ent | sed -n 's/^[ \t]*\([^ \t]\+\)[ \t]\+.\+$/\1/p')
    psql -1c "insert into nodes (id, host_id, host, cluster_id) values ('$node_id', '$host_id', '$host_ip', null)" > /dev/null 2>&1
    if [ $? -ne 0 ]; then 
        echo "Database error!"
        exit 1
    fi    
}

check_user() {
    id | grep -qE 'uid=[0-9]+\(vstoradmin\)' || {
        echo "Script should be executed on behalf of vstoradmin user"
        exit 3
    }
}

check_user
parse_opt $*
resolve_host $HOST_NAME
get_node_id $hostname:$agent_port
get_host_id $hostname:$agent_port
register_node
echo "Node $hostname has been registered"


