#!/bin/bash

# @PREAMBLE_START@

# This section is copied from preamble.sh (automatically, during build) and
# should not be edited in place.

# turn on echo for debuging.
if [ ! -z "${VERT_DEBUG_PREAMBLE:-}" ]; then set -x; else set +x; fi
: '# Preamble begin'
: '# # Standardizing shell'
unset IFS # default word splitting on whitespace
set +o history # disable history. Should be default, but some reports otherwise
set -u # disallow unset variables

# note: these two vars are reset by vars.bash, but necessary to get there.
VERT_D=${VERT_VERT_D:-'/opt/vertica'}
BINLIB_D=${VERT_BINLIB_D:-"$VERT_D/share/binlib"}
source "$BINLIB_D/include/vars.bash"
source "$BINLIB_D/include/common_func.bash"
source "$BINLIB_D/include/self_vars.bash"

: '# Preamble end'
set +x # turn echo off
# @PREAMBLE_END@

function usage() {
    v_here_echo << HEREDOC
$SELF_SHORTNAME: Create a private ssh key or export an existing 'id_rsa'

Usage: ./$SELF_SHORTNAME -f KEYFILE -u USER

KEYFILE:  A SSH private key file, not password protected.
USER:     The user. Should be the current user.

Exit status:
    0   if success
    1   for general improper usage errors or internal errors
HEREDOC
}

KEYFILE=""
USERNAME=""
while getopts :0f:u: OPTVAL; do
    case "$OPTVAL" in
        h )
            usage
            exit 0
            ;;
        f )
            KEYFILE="$OPTARG"
            ;;
        u )
            USERNAME="$OPTARG"
            ;;
        \? )
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
    esac
done

shift $(( $OPTIND - 1 ))

if [ "$#" != "0" ]; then
    echo "Unexpected arguments: $*" >&2
    usage >&2
    exit 1
fi

if [ "$KEYFILE" = "" ]; then
    echo "No key file provided (-k required)" >&2
    usage >&2
    exit 1
fi

if [ "$USERNAME" = "" ]; then
    echo "No user name provided (-u required)" >&2
    usage >&2
    exit 1
fi

eval SSH_DIR=~$USERNAME/.ssh # eval to expand the ~

if [ "${SSH_DIR:0:1}" != '/' ]; then
    echo "Invalid user. ~$USERNAME did not expand to an absolute path" >&2
    exit 1
fi

EXISTING_KEYFILE="$SSH_DIR/id_rsa"

if [ -f "$EXISTING_KEYFILE" ]; then
    if ! "$BIN_INSTALL" -T --owner "$USERNAME" --mode 600 "$EXISTING_KEYFILE" "$KEYFILE"; then
        echo "Key file found, but could not export" >&2
        exit 1
    fi
    exit 0
fi

if ! "$BIN_SSH_KEYGEN" -t rsa -q -f "$KEYFILE" -N ''; then
    echo "Failed to create key file" >&2
    exit 1
fi
