cnssh: Copy config array to runtime array and work on that instead

This commit is contained in:
David Thurstenson 2021-05-06 17:16:45 -05:00
parent 7e9aa6fdb5
commit e8da138c36
1 changed files with 31 additions and 21 deletions

View File

@ -24,9 +24,16 @@ cnssh() { # Helper for sshing into Crestron devices
####
# Config init
# Initialize runtime config array
declare -A conf
# Initialize config array if it doesn't already exist
if [[ ! -v cnssh_conf[@] ]]; then
declare -A cnssh_conf
else
for opt in "${!cnssh_conf[@]}"; do
conf[$opt]=${cnssh_conf[$opt]}
done
fi
# Initialize and populate default config array
@ -37,6 +44,14 @@ cnssh() { # Helper for sshing into Crestron devices
[pass]=""
)
# Apply defaults to running config
for opt in "${!dconf[@]}"; do
# Don't apply the default if it's already set
if [[ ! -v conf[$opt] ]]; then
conf[$opt]=${dconf[$opt]}
fi
done
declare -A sshopts
sshopts=(
[StrictHostKeyChecking]="no"
@ -55,7 +70,7 @@ cnssh() { # Helper for sshing into Crestron devices
while getopts ":u:" opt; do
case $opt in
u)
cnssh_conf[uname]="$OPTARG"
conf[uname]="$OPTARG"
;;
\?)
echo "Unknown option -$OPTARG"
@ -73,38 +88,30 @@ cnssh() { # Helper for sshing into Crestron devices
# Set the address based on the first
# arg if not already set in config array
if [[ ! -v cnssh_conf[addr] ]]; then
cnssh_conf[addr]="$1"
if [[ ! -v conf[addr] ]]; then
conf[addr]="$1"
shift 1
fi
# Set the command as the rest of argv
# if not already set in config array
if [[ ! -v cnssh_conf[cmd] ]]; then
cnssh_conf[cmd]="$*"
if [[ ! -v conf[cmd] ]]; then
conf[cmd]="$*"
fi
# Apply defaults to running config
for opt in "${!dconf[@]}"; do
# Don't apply the default if it's already set
if [[ ! -v cnssh_conf[$opt] ]]; then
cnssh_conf[$opt]=${dconf[$opt]}
fi
done
# Set ssh user name
sshopts[User]="${cnssh_conf[uname]}"
sshopts[User]="${conf[uname]}"
# Set ssh host if not using sftp mode
case ${cnssh_conf[method]} in
case ${conf[method]} in
ssh)
:
;;
sftp)
unset "cnssh_conf[cmd]"
unset "conf[cmd]"
;;
*)
echo "Unknown method: ${cnssh_conf[method]}"
echo "Unknown method: ${conf[method]}"
;;
esac
@ -115,15 +122,15 @@ cnssh() { # Helper for sshing into Crestron devices
####
# Main
sshpass -p "${cnssh_conf[pass]}" \
"${cnssh_conf[method]}" \
sshpass -p "${conf[pass]}" \
"${conf[method]}" \
$( # Format sshopts as a string that an ssh program understands
for opt in "${!sshopts[@]}"; do
printf '%s %s=%s ' "-o" "$opt" "${sshopts[$opt]}"
done
) \
"${cnssh_conf[addr]}" \
"${cnssh_conf[cmd]}"
"${conf[addr]}" \
"${conf[cmd]}"
# Main
####
@ -141,4 +148,7 @@ cnsftp() {
cnssh_conf[addr]="$*"
cnssh
unset "cnssh_conf[method]"
unset "cnssh_conf[addr]"
}