summary refs log tree commit diff
path: root/bin
diff options
context:
space:
mode:
authorRobert Günzler <r@gnzler.io>2022-04-20 19:20:02 +0200
committerRobert Günzler <r@gnzler.io>2022-04-20 19:20:02 +0200
commitcda7455fe70731489650ef33ee4899e633adee34 (patch)
treefba292094667d517d90dc11e39266247116d8b4f /bin
parent704d9156e7e79071e8bf7eb5705d74c5853c5b78 (diff)
Add bin/b2
Diffstat (limited to 'bin')
-rwxr-xr-xbin/b263
1 files changed, 63 insertions, 0 deletions
diff --git a/bin/b2 b/bin/b2
new file mode 100755
index 0000000..c24b318
--- /dev/null
+++ b/bin/b2
@@ -0,0 +1,63 @@
+#!/bin/sh
+
+set -e
+
+cdn_uri=${B2CLI_CDN_URI:-cdn.example.com}
+bucket=${B2CLI_BUCKET:?missing bucket}
+b2_uri=${B2CLI_B2_URI:-f001.backblazeb2.com}
+
+canonical_uri() {
+	sed "s|${b2_uri}/file/${bucket}|${cdn_uri}/static|g"
+}
+
+list=
+delete=
+hash=
+while getopts H:ldh opt; do
+	case "$opt" in
+	l) list=1 ;;
+	d) delete=1 ;;
+	H) hash=${OPTARG} ;;
+	h | ?)
+		printf "usage: %s [-hld] [FILE] [DESTINATION]\n" "$(basename "$0")"
+		printf "\n"
+		printf "  -l       list\n"
+		printf "  -d       delete\n"
+		printf "  -H FILE  hash\n"
+		printf "\n"
+		printf "The default action is to put the FILE into the remote bucket\n"
+		exit 2
+		;;
+	esac
+done
+shift $((OPTIND - 1))
+
+file="${1}"
+dest=${2:-"$(basename "${file}")"}
+
+if [ -n "$list" ]; then
+	for lnk in $(rclone lsf -R b2:${bucket}/ | sort); do
+		echo "https://${b2_uri}/file/${bucket}/${lnk}" | canonical_uri
+	done
+	exit 0
+fi
+
+if [ -n "$delete" ]; then
+	rclone deletefile b2:${bucket}/"${file}"
+	printf "deleted: %s\n" "${file}" >&2
+	exit 0
+fi
+
+if [ -n "$hash" ]; then
+	ext="$(echo "${file}" | rev | cut -d\. -f1 | rev | sed -e "s#${file}##")"
+	[ -n "$ext" ] && ext=".${ext}"
+	[ "$hash" = "self" ] && hash=$file
+	sum=$(md5sum "$hash" | cut -d\  -f1)
+	dest=$(echo "${dest}" | sed -e "s#$(basename "${file}")#${sum}${ext}#")
+fi
+
+rclone copyto "${file}" b2:${bucket}/"${dest}" >&2
+
+b2_share_link="https://${b2_uri}/file/${bucket}/${dest}"
+echo "${b2_share_link}" | sed "s|${b2_uri}|${cdn_uri}|" >&2
+echo "${b2_share_link}" | canonical_uri