summary refs log tree commit diff
path: root/bin/b2
blob: 07d1976d9a7c9660aca87126ffc3c7439e4adfbf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/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 Hldh opt; do
	case "$opt" in
	l) list=1 ;;
	d) delete=1 ;;
	H) hash=1 ;;
	h | ?)
		printf "usage: %s [-hld] [FILE] [DESTINATION]\n" "$(basename "$0")"
		printf "\n"
		printf "  -l       list\n"
		printf "  -d       delete\n"
		printf "  -H       hash as filename\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}"
	sum=$(md5sum "$file" | 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