summaryrefslogtreecommitdiffstats
path: root/gomfload.sh
blob: 3d18861059a31e54190b7b49d6e95be4bb867041 (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
#!/bin/sh

# This software is released into public domain.
# It is provided "as is", without warranties or conditions of any kind.
# Anyone is free to use, modify, redistribute and do anything with this software.

# requires: POSIX sh, curl, tr

service="${GOMF_HOST:-https://example.com/}"

prog="$(basename "$0")"
stdin=1

usage() {
	printf "Usage: %s < file\n" "$prog"
	printf "       command | %s\n" "$prog"
	printf "       %s file1 file2 file3 ...\n" "$prog"
	printf "\n"
	printf "Options (applies for all files following the flag):\n"
	printf "  -S,  --service=ADDR  uses ADDR as the service URL\n"
	printf "  -h,  --help          display this help and exit\n"
	printf "  --                   stop processing options and treat all following arguments as filenames\n"
	exit
}

upload() {
	file=''
	if [ $# -ge 1 ]; then
		filename="$(printf "%s" "$(basename "$1")" | tr -c -d 'a-zA-Z0-9_.+ -')"
		if [ -n "$filename" ]; then
			file=";filename=$filename"
		fi
	fi
	url="$(curl --progress-bar -F "files[]=@-$file" "${service%/}/upload.php?output=gyazo")"
	case "$url" in
		http*)
			printf "%s\n" "$url"
			;;
		?*)
			printf "%s: error: %s\n" "$prog" "$url" >&2
			return 1
			;;
		'')
			return 1
			;;
	esac
}

upload_file() {
	stdin=0
	url="$(upload "$1" < "$1")"
	if [ $? -ne 0 ]; then
		exit 1
	fi
	printf "%s: %s\n" "$1" "$url"
}

while [ $# -gt 0 ]; do
	case "$1" in
		-h|--help)
			usage
			;;

		-S|--service)
			if [ $# -ge 2 ]; then
				service="$2"
				shift
			else
				printf "%s: option '%s' requires an argument\n" "$prog" "$1" >&2
				exit 2
			fi
			;;

		-S?*)
			service="${1#-S}"
			;;

		--service=*)
			service="${1#*=}"
			;;

		--)
			shift
			break
			;;

		-?*)
			printf "%s: unrecognized option '%s'\n" "$prog" "$1" >&2
			exit 2
			;;

		*)
			upload_file "$1"
			;;
	esac

	shift
done

while [ $# -gt 0 ]; do
	upload_file "$1"
	shift
done

if [ "$stdin" -ne 0 ]; then
	upload
	exit $?
fi