#!/usr/bin/env bash
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"

help_formatted (){
	echo -e 'Usage: dokku ssh-keys[:COMMAND]'
	echo ''
	echo 'Manage public ssh keys that are allowed to connect to Dokku'
	echo ''
	echo 'Additional commands:'
	help_content_func | sort | column -c2 -t -s,
}

help_content_func () {
      declare desc="return ssh-keys plugin help content"
      cat<<help_content
    ssh-keys, Manage public ssh keys that are allowed to connect to Dokku
    ssh-keys:list, List of all authorized dokku public ssh keys
    ssh-keys:add <name> [/path/to/key], Add a new public key by pipe or path
    ssh-keys:remove <name>, Remove SSH public key by name
help_content
    }

verify_ssh_key_file() {
  declare desc="Test that public key is valid"
  [[ -s ${DOKKU_ROOT}/.ssh/authorized_keys ]] || dokku_log_fail "No public keys found."
  local key line=0
  while read key ; do
    line=$((line + 1))
    ssh-keygen -l -f /dev/stdin <<< "$key" &> /dev/null || dokku_log_fail "${DOKKU_ROOT}/.ssh/authorized_keys line $line failed ssh-keygen check."
  done <"${DOKKU_ROOT}/.ssh/authorized_keys"
}

verify_ssh_key_exists() {
  declare desc="Test that public key exists"
  [[ -e ${DOKKU_ROOT}/.ssh/authorized_keys ]] || dokku_log_fail "No public keys found."
}
