Files
up-and-share/uas.sh

63 lines
1.7 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
2015-07-07 16:26:41 +03:00
# This script enables users to easily upload files via a SSH connection and creates a link to
# download them.
# SPDX-License-Identifier: GPL-3.0-only
# SPDX-FileCopyrightText: 2019 Max Mehl <https://mehl.mx>
2015-07-07 16:26:41 +03:00
2019-03-12 15:10:30 +01:00
BASENAME=$(basename "$0")
2015-07-07 16:26:41 +03:00
# Load config
BINDIR="$(dirname "$(readlink -f "$0")")"
# Test if config.cfg exists and set needed variables
if [ ! -e "$BINDIR"/config.cfg ]; then echo "Missing config.cfg file. Edit and rename config.cfg.sample"; exit 1; fi
source "$BINDIR"/config.cfg
2015-07-07 16:26:41 +03:00
if [ "$1" = "" ]; then
echo "Usage: $BASENAME <file-to-upload> [<subdirectory>]"
exit 1
2015-07-07 16:26:41 +03:00
fi
# Transform to full path
2019-03-12 15:10:30 +01:00
# file.pdf or /path/to/file.pdf
2015-07-07 16:26:41 +03:00
FILE="$1"
2019-03-12 15:10:30 +01:00
# -> file.pdf
FILE_NAME="$(basename "${FILE}")"
# Get subdirectory if given
if [ "$2" != "" ]; then
SSH_PATH="${SSH_PATH}/${2}"
URL="${URL}/${2}"
elif [ "$SUBDIR_DEFAULT" != "" ]; then
SSH_PATH="${SSH_PATH}/${SUBDIR_DEFAULT}"
URL="${URL}/${SUBDIR_DEFAULT}"
fi
2015-07-07 16:26:41 +03:00
2019-03-12 15:10:30 +01:00
# Check whether file actually exists locally
if [ ! -e "${FILE}" ]; then
echo "File ${FILE} does not exist locally."
2015-07-07 16:26:41 +03:00
exit 1
fi
# constuct file name, and replace spaces by underscores
DEST="${FILE_NAME// /_}"
# Check if file is existent remotely
cmd="test -e \"${SSH_PATH}\"/\"${DEST}\""
# Check if file does already exist with this name
if ssh -q "${SSH_HOST}" "${cmd}"; then
echo "File ${DEST} already exists on the host. Please rename the file or choose a different name."
exit 1
fi
2015-07-07 16:26:41 +03:00
2019-03-12 15:10:30 +01:00
# Upload file
if ! scp "$FILE" "${SSH_HOST}":"${SSH_PATH}"/"${DEST}"; then
echo "Error uploading file. Please check your connection and configuration."
exit 1
fi
2015-07-07 16:26:41 +03:00
# Output download link
echo "File has been uploaded. Download link:"
echo "$URL/$DEST"
exit 0