#!/bin/bash -e
#
# THIS FILE IS GOING TO BE EXECUTED ON ANY CFG NODES (MCP1).
#
RUN_DIR=$(cd $(dirname "$0") && pwd)
TOP_DIR=$(cd $(dirname $RUN_DIR/../../) && pwd)

. $TOP_DIR/globals
. $TOP_DIR/functions-common

function get_nova_key_archive_path {
    echo "/tmp/nova-ssh.tar.gz"
}

function update_nova_ssh_keys {
    local salt_out
    local key_directory='/var/lib/nova/.ssh'
    local temp=$(mktemp -d)
    local live_compute=$(get_first_active_minion -C "I@nova:compute")

    info "Packing nova repository ${key_directory} $live_compute"
    salt "$live_compute" cmd.run "mkdir $temp; cp ${key_directory}/id_rsa  $temp/private; cp ${key_directory}/authorized_keys $temp/public; "
    salt "$live_compute" archive.tar czf $(get_nova_key_archive_path) $temp || die $LINENO "Failed to pack nova keys $key_directory"
    info "Nova keys are packed"

    salt "$live_compute" cp.push $(get_nova_key_archive_path) upload_path=\"$(get_nova_key_archive_path)\" remove_source=True
    local_keys_archive="/var/cache/salt/master/minions/${live_compute}/files/$(get_nova_key_archive_path)"

    info "Nova keys are copied"

    local extract_local=$(mktemp -d)
    local secret_folder=$(mktemp -d)
    tar -xzf ${local_keys_archive} -C ${extract_local}/ || die $LINENO "Failed to extract archive with keys: $local_keys_archive"
    mkdir -p ${secret_folder}/secret
    #convert private key to oneliner enclosed in double quotes to fit format of key generated by os controller
    python3 -c "with open(\"${extract_local}/${temp}/private\") as f: print((repr(f.read())).replace('\'', '\"'))" > ${secret_folder}/secret/private
    #remove trailing space, enclose public key in double quotes to fit format of key generated by os controller
    cat ${extract_local}/${temp}/public | sed 's/[ \t]*$//' | sed 's/^/"/;s/$/"/' > ${secret_folder}/secret/public

    kubectl delete secret generated-nova-ssh-creds -n openstack || info "Secret doesnt exists"
    kubectl create secret generic generated-nova-ssh-creds --from-file=${secret_folder}/secret -n openstack || die $LINENO "Failed to update nova ssh key generated-nova-ssh-creds"
    info "Nova ssh keys were updated successfully"
}


function restart_nova_computes {
    info "Restarting nova computes on MCP2"
    kubectl delete pods -l application=nova,component=compute -n openstack && die $LINENO "No nova pods found"
    info "Nova computes was restarted"
}

update_nova_ssh_keys
restart_nova_computes
