wp-scp/copy.sh

66 lines
1.6 KiB
Bash

#!/usr/bin/env sh
fatal() {
echo "[ERROR] $1"
[ -n "$2" ] && exit "$2" || exit 1
}
info() {
echo "[INFO] $1"
}
# dropbear SSH uses a whacky private key format. I can't imagine anyone likes this, so read a normal
# one from the input (which needs to be a string anyways) and let dropbear figure it out
create_key_from_env() {
if [ ! -d "$HOME"/.ssh ]; then
mkdir "$HOME"/.ssh
fi
info "Creating key from input variable"
echo "${PLUGIN_SSH_PRIVATE_KEY}" >"$HOME"/.ssh/id_rsa
chmod 600 "$HOME"/.ssh/id_rsa
dropbearconvert openssh dropbear "$HOME"/.ssh/id_rsa "$HOME"/.ssh/id_dropbear
chmod 600 "$HOME"/.ssh/id_dropbear
}
if [ -z "${PLUGIN_REMOTE_USER}" ]; then
fatal "Must specify remote user" 1
fi
if [ -z "${PLUGIN_REMOTE_HOST}" ]; then
fatal "Must specify remote host" 2
fi
if [ -z "${PLUGIN_REMOTE_PORT}" ]; then
PLUGIN_REMOTE_PORT=22
fi
if [ -z "${PLUGIN_REMOTE_PATH}" ]; then
fatal "Must specify remote path" 3
fi
if [ -z "$PLUGIN_SSH_PRIVATE_KEY" ]; then
fatal "Must provide private key for authentication" 4
fi
if [ -z "$PLUGIN_FILE" ]; then
fatal "Must provide source file for transfer" 5
fi
create_key_from_env
scp -o StrictHostKeyChecking=accept-new \
-P "${PLUGIN_REMOTE_PORT}" \
-i "$HOME"/.ssh/id_dropbear \
"${PLUGIN_FILE}" \
"${PLUGIN_REMOTE_USER}"@"${PLUGIN_REMOTE_HOST}":"${PLUGIN_REMOTE_PATH}" >/dev/null 2>&1
scp_status=$?
info "Cleaning up SSH keys"
rm -r "$HOME"/.ssh
if [ "$scp_status" -ne 0 ]; then
fatal "Transfer failed with exit code $scp_status" $scp_status
fi
info "Transfer completed"