Improve bash formatting
[mercuryms.git] / listener.sh
1 #!/bin/bash
2 # DATA indices are defined by the mercuryms-send program, and are from mercuryms-sqlite
3 # 0: MEDIA.ID
4 # 1: MEDIA.PHONE_NUMBER
5 # 2: MEDIA.URI
6 while IFS='|' read -a DATA DATA_STR; do
7 # Check if the phone number has an existing folder.
8 # WebDAV responds to a PROPFIND with a 207 if a resource exists.
9 # It responds 404 otherwise, but we will attempt to create on any other code.
10 # AWK exits with inverted exit codes to use the && bash short circuit.
11 curl --silent \
12 --include \
13 --user $USER:$($PW_COMMAND) \
14 "$HOST/remote.php/dav/files/$USER/${DATA[1]}" \
15 -X PROPFIND \
16 --data '<?xml version="1.0" encoding="UTF-8"?>
17 <d:propfind xmlns:d="DAV:">
18 <d:prop>
19 <d:resourcetype/>
20 </d:prop>
21 </d:propfind>' \
22 | awk '/HTTP\// {if ($2 == "207") { exit 1; } else { exit 0; }}' \
23 && curl --silent \
24 --user $USER:$($PW_COMMAND) \
25 -X MKCOL "$HOST/remote.php/dav/files/$USER/${DATA[1]}"
26 # Download the media we were sent from the URI.
27 # Upload it to Nextcloud and respond with the ID in the database
28 # so that we can record success.
29 IDENTIFIER=$(echo ${DATA[2]} | awk -F/ '{print $NF}')
30 curl --silent \
31 --location ${DATA[2]} \
32 | curl --silent \
33 --user $USER:$($PW_COMMAND) \
34 --upload-file - \
35 "$HOST/remote.php/dav/files/$USER/${DATA[1]}/$IDENTIFIER.jpg" && echo ${DATA[0]} received.
36 done
37
38 exit 0