-
Notifications
You must be signed in to change notification settings - Fork 33
/
magnet
executable file
·42 lines (34 loc) · 1.1 KB
/
magnet
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
#!/bin/bash
typeset -A dst_dirs
while [[ -n "$1" ]]; do
case "$1" in
--dst-*)
dst_type=${1#--dst-}
shift
dst_dirs[$dst_type]=$1 ;;
-x) set -x ;;
*) break ;;
esac
shift
done
[[ -z "$1" ]] && { echo >&2 "Expecting at least one link"; exit 1; }
coproc awk '
match($0, /\<xt=urn:btih:([0-9a-zA-Z]+)/, a)\
{printf("bt %s.magnet\n", a[1]); fflush(); next}
{ print $0 |& "md5sum"; close("md5sum", "to"); "md5sum" |& getline
printf("misc %s.magnet\n", $1); fflush() }'
err=
for src in "$@"; do
echo "$src"> /dev/fd/"${COPROC[1]}"
read dst_type dst_basename < /dev/fd/"${COPROC[0]}"
[[ -n "${dst_dirs[$dst_type]}" ]] && dst="${dst_dirs[$dst_type]}/${dst_basename}"\
|| { printf >&2 "ERROR: No --dst-$dst_type specified for link: %q\n" "$src"; dst=; }
[[ -n "$dst" ]] || {
echo >&2 "ERROR: Failed to classify link, skipping" \
"(type: ${dst_type}, basename: ${dst_basename})"; err=true; continue; }
echo "$src" >"$dst" || {
echo >&2 "ERROR: Failed to write to a destination file (${dst})"; err=true; }
done
eval "exec ${COPROC[0]}>&- ${COPROC[1]}>&-"
wait
[[ -z "$err" ]] && exit 0 || exit 1