1#!/usr/bin/env bash
2
3# Adapted from:
4# - https://github.com/tus/tus.io/issues/96
5
6if [ ! -f "${1}" ]; then
7 echo -e "\n\033[1;31m✘\033[0m First argument needs to be an existing file.\n"
8 exit 1
9fi
10
11if [ -z "${2}" ]; then
12 echo -e "\n\033[1;31m✘\033[0m Second argument needs to be the TUS server's URL.\n"
13 exit 1
14fi
15
16file=${1}
17TUS_URL=${2}
18filename=$(basename "${file}" | base64)
19filesize="$(wc -c <"${file}")"
20
21# Apparently 'Location: ..' is terminated by CRLF. grep and awk faithfully
22# preserve the line ending, and the shell's $() substitution strips off the
23# final LF leaving you with a string that just ends with a CR.
24#
25# When the CR is printed, the cursor moves to the beginning of the line and
26# whatever gets printed next overwrites what was there.
27# ... | tr -d '\015'
28location=$(curl \
29 --silent --show-error \
30 -I \
31 -X POST \
32 -H "Tus-Resumable: 1.0.0" \
33 -H "Content-Length: 0" \
34 -H "Upload-Length: ${filesize}" \
35 -H "Upload-Metadata: name ${filename}" \
36 "${TUS_URL}" | grep 'Location:' | awk '{print $2}' | tr -d '\015')
37
38if [ -n "${location}" ]; then
39 curl \
40 -X PATCH \
41 -H "Tus-Resumable: 1.0.0" \
42 -H "Upload-Offset: 0" \
43 -H "Content-Length: ${filesize}" \
44 -H "Content-Type: application/offset+octet-stream" \
45 --data-binary "@${file}" \
46 "${location}" -v
47else
48 echo -e "\n\033[1;31m✘\033[0m File creation failed..\n"
49 exit 1
50fi