#!/bin/sh

po_domain="alterator-pve"
alterator_api_version=1

. alterator-sh-functions

# files
pve_sysconf_dir="/etc/pve"
pve_corosync_conf="$pve_sysconf_dir/corosync.conf"

get_host_ip_addr()
{
    local via=$(ip route show 0/0 | grep -o 'via [0-9.]\+' | awk '{ print $2 }')
    local ip_addr=$(ip route get $via | grep -o 'src [0-9.]\+' | awk '{ print $2 }')
    echo $ip_addr
}

can_resolve_local_ip_addr()
{
    local ip_addr=$(get_host_ip_addr)

    [ -z "$ip_addr" ] && return 1

    getent hosts $(hostname -s) | grep -q "$ip_addr"
}

add_ip_to_hosts()
{
    local ip_addr=$(get_host_ip_addr)

    cat <<EOF >> /etc/hosts
$ip_addr      $(hostname)	$(hostname -s)
EOF
}

is_in_cluster()
{
    if [[ -f "$pve_corosync_conf" ]]; then
	tmpstr="$(grep cluster_name "$pve_corosync_conf")"
	if [[ -n "$tmpstr" ]]; then
	    cluster_name="$(echo "$tmpstr" | cut -f2 -d: | sed -e 's/^\s\+//')"
	    echo "$cluster_name"
	fi
    fi
}

is_pve_cluster_running()
{
    if service pve-cluster status >&2; then
	echo true
    else
	echo false
    fi
}

start_pve_cluster()
{
    service pve-cluster start >&2
}

gengerate_sshkeys()
{
    local SSH_ALGORITHM=${1:-rsa}; shift
    local SSH_BITS=${1:-4096}; shift
    local SSH_COMMENT=${1:-"PVE cluster control"}; shift
    local SSH_KEYFILE="/root/.ssh/pve_key"
    local AUTHORIZED_KEYS="/root/.ssh/authorized_keys" # should be get from sshd_config

    out="$(ssh_keygen -b "$SSH_BITS" -t "$SSH_ALGORITHM" -C "$SSH_COMMENT" \
		-f "$SSH_KEYFILE")"

    cat "$SSH_KEYFILE" >> "$AUTHORIZED_KEYS"
}

pve_create()
{
    local NAME="$1"; shift

    # TODO: we should check parameter NAME
    local log="$(pvecm create $NAME)"
    if [ $? != 0 ]; then
	echo "bad" >&2
    fi

    echo $log >&2
}

pve_add_to_cluster()
{
    generate_sshkeys

    # tobe implemented
}

service_pve_cluster()
{
    case $1 in
	start)
	    can_resolve_local_ip || add_ip_to_hosts
	    service pve-cluster start
	    ;;
	*)
	    service pve-cluster $1
	    ;;
    esac
}

on_message()
{
    case "$in_action" in
	new)
	    [ -n "$in_pve_service" ] && service_pve_cluster $in_pve_service
	    ;;
	read)
	    local cluster_name=$(is_in_cluster)
	    write_bool_param cluster_run $(is_pve_cluster_running)
	    if [[ -n "$cluster_name" ]]; then
		write_bool_param in_cluster "true"
		write_string_param cluster_name "$cluster_name"
		write_string_param pve_manager_status "$(service pve-manager status)"
		write_string_param pve_cluster_status "$(service pve-cluster status)"
	    else
		write_bool_param in_cluster "false"
	    fi
	    ;;
	write)
	    echo "$(set|grep -a "in_")" >&2
	    if [ -n "$in_cluster_name" ]; then
		out="$(pve_create "$in_cluster_name")"
	    fi
	    ;;
	list)
	    ;;
    esac
}

message_loop
