summaryrefslogtreecommitdiff
path: root/forwarddown.in
blob: 31b44876842f5af2986c9bc5aa75a8eed0b0cbe9 (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
109
110
111
#!/bin/bash

[ -r "#ETCDIR#/backup.conf" ] && \
  . "#ETCDIR#/backup.conf"

usage()
{
  >&2 echo \
'Usage:  forwarddown key-id date backup-id1 backup-id2 ...
Write encrypted, compressed tar from backed up files not newer than date to stdout.

Options:
  key-id        key id of key to encrypt to
  date          backup should not be newer than the given date
  backup-id[n]  backups to restore
#HELPTEXT#              #'
  [ -z "$1" ] && exit 1
  exit $1
}

if [ $# -eq 1 ]; then
  if [ "$1" == "--help" ]; then
    usage 0
  elif [ "$1" == "--version" ]; then
    echo '#VERSION#'
    exit
  fi
fi

if [ $# -lt 3 ]; then
  usage
fi

key_id=$(
  printf '%s\n' "$1" \
  | tr '[:lower:]' '[:upper:]'
)
shift

if ! gpg --list-keys --with-colon "${key_id}" \
| grep -qxF 'fpr:::::::::'"${key_id}"':'; then
  >&2 printf 'Cannot find gpg key with fingerprint "%s"\n' "${key_id}"
  usage
fi

if ! date=$(date -u '+%Y_%m_%d' -d"${1}"); then
  >&2 printf 'Cannot parse date "%s"\n' "${1}"
  usage
fi
shift

forwarddown_dirs=()

for backup_id in "$@"; do
  if [ -z "${backups[${backup_id}]}" ]; then
    >&2 printf 'backup id "%s" is unknown\n' "${backup_id}"
    usage
  fi
  forwarddown_dirs+=("${backups[${backup_id}]## *}")
done

date=$(
  {
    find "${forwarddown_dirs[@]%% *}" -mindepth 1 -maxdepth 1 -type d -printf '0 %f\n'
    printf '1 %s\n' "${date}"
  } \
  | sort -k2,2 -k1,1 \
  | sed '
    s/^0 //
    t
    /^1 / q
  ' \
  | uniq -c \
  | sed '
    s/^\s*'"${#forwarddown_dirs[@]}"'\s\+//
    t
    d
  ' \
  | tail -n1
)

transforms=(
  $(
    for backup_id in "$@"; do
      printf -- '--transform=s@^%s/%s/@%s/%s/@\n' \
        "${backups[${backup_id}]%% *}" \
        "${date}" \
        "${date}" \
        "${backup_id}"
    done
  )
)

directories=(
  $(
    for backup_id in "$@"; do
      printf '%s/%s/\n' \
        "${backups[${backup_id}]%% *}" \
        "${date}"
    done
  )
)

tar \
  -c \
  -f - \
  --absolute-names \
  "${transforms[@]}" \
  "${directories[@]}" \
| pigz --best -c - \
| gpg -e -r "${key_id}" -o - -