summaryrefslogtreecommitdiff
path: root/custom/recv-media.sh
blob: 2f291dcce4819ac9108d148a364a969bfdb22c29 (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
#!@zsh@/bin/zsh

pid=$?

exec 1> >(@utillinux@/bin/logger --id=$pid -t recv-media -p user.notice)
exec 2> >(@utillinux@/bin/logger --id=$pid -t recv-media -p user.error)

[[ -z "$1" || -z "$2" ]] && exit 2

dir=@mediadir@
group=$(@coreutils@/bin/stat -c '%G' $dir)
tmpFile="${dir}/.tmp/${1:t}"
target="${dir}/${1:t}"

if [[ -n "${3}" ]]; then
  target="${dir}"/$(@coreutils@/bin/base64 -d <<<${3})
fi

# @utillinux@/bin/logger --id=$pid -t recv-media -p user.debug <<EOF
# $(id)
# $(stat ${dir})
# $(stat ${1})
# $(echo ${2})
# EOF

if [[ $(@coreutils@/bin/id -Gn) != *"$group"* ]]; then
  printf "Groups are ‘%s’. Trying to switch primary group to ‘%s’..." $(@coreutils@/bin/id -Gn) $group
  exec -- @wrapperdir@/sg $group "$0 $*"
fi

typeset -a failures
failures=()

(
  if ! @coreutils@/bin/cp -lnv --preserve=all "$1" "${target}"; then
    @coreutils@/bin/mkdir -pv "${tmpFile:h}" || failures+="mkdir"

    @utillinux@/bin/ionice -c 3 -t @coreutils@/bin/cp -vn --preserve=all "$1" "${tmpFile}" && @coreutils@/bin/mv -v "${tmpFile}" "${target}" || failures+="cp & mv"
  fi
  @coreutils@/bin/touch -c -m -t "$2" "${target}" || failures+="touch"
)

if @donotify@ && [[ $#failures -gt 0 ]]; then
  printf "%s\n%s\n%s" "${target:t}" "Failed to download" ${(j:, :)failures} | @notify@ -a recv-media -u Critical
fi

if @donotify@; then
  (
    summary=""

    if @showtitle@; then
      summary=$(@ffmpeg@/bin/ffmpeg -i "${target}" -f ffmetadata pipe:1 2>/dev/null | sed -r '/\[CHAPTER\]/q; /^title=/!d; s/^title=//; s/(^\s*|\s*$)//g')
    fi

    if [[ -z "${summary}" ]]; then
      summary=${target:t}
    fi

    printf "%s\n%s\n" "${summary}" "" | @notify@ -a recv-media || true
  ) || true
fi