summaryrefslogtreecommitdiff
path: root/bin/rupload
blob: 74c943ccb48cad63485e16ee5f255774f559c80a (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/bin/sh

REMOTE="do"
URLBASE="https://ubq323.website/files/"
REMOTEDIR="/srv/web/ubq/files/"

if [ $# -eq 0 ]; then
	printf '%s\n' "usage: $0 [-n] [-p] [-x EXT | -r NAME | -R] FILENAME" >&2
	printf '\t%s\n' "-n: dry run (don't actually upload anything)" >&2
	printf '\t%s\n' "-p: print uploaded url instead of copying to clipboard and notifying" >&2
	printf '\t%s\n' "-x EXT: set extension to EXT on uploaded filename" >&2
	printf '\t%s\n' "-r NAME: set remote name to NAME including extension" >&2
	printf '\t%s\n' "-R: set remote name to basename of FILENAME" >&2
	exit 1
fi

dry_run=0
samename=0
printurl=0
saved_stdin=0
override_rname=
while [ $# -gt 1 ]; do
	if [ "$1" = "-x" ]; then
		override_ext=".$2"
		shift 2
	elif [ "$1" = "-n" ]; then
		dry_run=1
		shift
	elif [ "$1" = "-p" ]; then
		printurl=1
		shift
	elif [ "$1" = "-r" ]; then
		override_rname="$2"
		shift 2
	elif [ "$1" = "-R" ]; then
		samename=1
		shift
	else
		printf "%s: unrecognized argument %s\n" "$0" "$1" >&2
		exit 2
	fi
done

target="$1"

if [ "$1" = "-" ]; then
	tempfile="$(mktemp /tmp/tmp_XXXXXXXXXXX)"
	# echo yeah "$tempfile"
	cat >"$tempfile"
	saved_stdin=1
	target="$tempfile"
fi

tidy_tempfile() {
	if [ "$saved_stdin" -eq 1 ]; then
		rm "$tempfile"
	fi
}

if [ ! -f "$target" ]; then
	printf "%s: file does not exist\n" "$target" >&2
	exit 1
fi

if [ "$samename" -eq 1 ]; then
	override_rname="$(basename "$target")"
fi


ext="${target#*.}"
if [ "$ext" = "$target" ]; then
	ext='.file'
	bname="$(basename "$target")"
else
	ext=".$ext"
	bname="$(basename "$target" "$ext")"
fi
ext=${override_ext:-$ext}

rbname="$(md5sum "$target"|cut -d' ' -f1|tr 'a-z' 'A-Z'|basenc -d --base16|basenc --base64url|head -c8)"
rname="${override_rname:-$rbname$ext}"

exists_already() {
	ssh "$REMOTE" stat "$REMOTEDIR$1" 2>/dev/null >/dev/null
	return $?
}

while exists_already "$rname"; do
	printf "%s exists already\n" "$rname" >&2
	rname="_$rname"
done

printf 'uploading to %s\n' "$rname" >&2
if [ "$dry_run" -eq 1 ]; then
	echo dryrun, not uploading anything
	tidy_tempfile
	exit 0
fi

scp -q "$target" "${REMOTE}:$REMOTEDIR$rname"
ssh "$REMOTE" chmod a+r "$REMOTEDIR$rname"

url="$URLBASE$rname"
if [ "$printurl" -eq 0 ]; then
	printf %s "$url" | wl-copy
	notify-send 'copied url to clipboard' "$url"
else
	printf '%s\n' "$url"
fi

tidy_tempfile