summaryrefslogtreecommitdiff
path: root/bin/extract-attachment
blob: 0cce7a139253e2284da9ce5dcd38867bfc681844 (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/bash

path=$(
  readlink -e "$(
    dirname "$(
      readlink -e "$0"
    )"
  )/.."
)

cnt=$(cat)

last_line=$(
  printf '%s\n' "${cnt}" \
    | tail -n1
)

if [ -z "${last_line##*--}" ]; then
  borders=$(
    printf '%s\n' "${cnt}" \
      | grep -nxF -- "${last_line%--}" \
      | cut -d: -f1
    printf '%s\n' '$'
  )
else
  borders=$(
    printf '%s\n' '1' '$'
  )
  last_line=$(
    printf '%s\n' "${content}" \
    | sha512sum \
    | awk '{print $1}'
  )
fi

start=''
decode=false
for end in ${borders}; do
  if [ -n "${start}" ]; then
    filtered_cnt=$(
      printf '%s\n' "${cnt}" \
        | sed -n "
          ${start} d
          ${end} { /^${last_line}\$/ d }
          ${start},${end} p
        " \
        | sed '
          :a
            $! N
            s/\s*\n\s\+/ /
          t a
          P
          D
        '
    )

    file_name=$(
      printf '%s\n' "${filtered_cnt}" \
        | sed '
          s@^Content-Disposition: \(attachment\|inline\); filename=\([^/[:space:]]\+\)$@\2@
          t
          s@^Content-Disposition: \(attachment\|inline\); filename="\([^/"]\+\)"$@\2@
          t
          s@^Content-Type: application/zip; name="\([^"]\+\.zip\)"$@\1@
          t
          d
        ' \
        | tr -d '"/' \
        | sed '
          s/^\s\+//
          s/\s\+$//
        ' \
        | tr '[:space:]' '_' \
        | sort -u
    )

    if printf '%s\n' "${filtered_cnt}" \
      | grep -qx '^Content-Transfer-Encoding: \(base\|BASE\)64\s*$' \
      && [ -n "${file_name}" ]; then
      decode=true
      break
    fi

  fi
  start="${end}"
done

if ! ${decode}; then
  file_name=$(
    printf '%s\n' "${cnt}" \
      | sha512sum \
      | awk '{print $1}'
  ).eml
fi

if ${decode}; then
  printf '%s\n' "${filtered_cnt}" \
    | sed -n '
      /^$/,$ {
        /^$/ d
        p
      }
    ' \
    | base64 -d
else
  printf '%s' "${cnt}"
fi \
  > "${path}/reports/${file_name}"