]> Sergey Matveev's repositories - dotfiles.git/blob - bin/bin/zsnap
Ability to send backup via FIFO
[dotfiles.git] / bin / bin / zsnap
1 #!/usr/bin/env zsh
2
3 set -e
4 setopt EXTENDED_GLOB
5
6 usage() {
7     cat <<EOF
8 Usage: $0 DATASET@SNAPPREFIX snap-initial
9        $0 DATASET@SNAPPREFIX snap
10        $0 DATASET@SNAPPREFIX sync-initial DST
11        $0 DATASET@SNAPPREFIX sync DST
12        $0 DATASET@SNAPPREFIX clean COUNT
13        FIFO=1
14 EOF
15     exit 1
16 }
17
18 enccmd=(~stargrave/bin/age -R /home/stargrave/.age/general.pub)
19
20 [[ $# -ge 2 ]] || usage
21
22 what=$1
23 action=$2
24
25 zmodload -F zsh/datetime b:strftime
26 now=$(strftime %Y%m%d%H%M)
27 [[ $what =~ / ]] && depth=1 || depth=${#${(s./.)what}}
28 snaps=$(zfs list -t snap -d $depth -o name -H | grep $what | sort -nr)
29 snaps=(${(f)snaps})
30 latest=${snaps[1]}
31 latest_filename=${latest:gs#/#%}
32 dst=$3
33 [[ -z $FIFO ]] || {
34     mkfifo $dst/$latest_filename.zfs.zst.age
35     echo $dst/$latest_filename.zfs.zst.age
36 }
37
38 case $action in
39     snap-initial)
40         zfs snap -r $what-$now
41         print $what-$now
42         ;;
43     snap)
44         [[ -n $latest ]]
45         [[ "$what-$now" != $latest ]]
46         zfs snap -r $what-$now
47         print $what-$now
48         ;;
49     sync-initial)
50         [[ -d $dst ]] || usage
51         setopt PIPE_FAIL
52         zfs send -Rwv $latest | zstdmt | $enccmd > $dst/$latest_filename.zfs.zst.age
53         sync
54         touch $dst/$latest_filename.from
55         ;;
56     sync)
57         [[ -d $dst ]] || usage
58         latest_dst=($dst/*.from~$dst/.*(.Onn[1]))
59         [[ $latest_dst ]]
60         latest_dst=${latest_dst[1]}
61         latest_dst=${${latest_dst##*/}%.from}
62         [[ $latest_dst != $latest_filename ]]
63         setopt PIPE_FAIL
64         set -x
65         zfs send -Rwv -i ${latest_dst:gs#%#/} $latest | zstdmt | $enccmd > \
66             $dst/$latest_filename.zfs.zst.age
67         set +x
68         sync
69         print $latest_dst > $dst/$latest_filename.from
70         ;;
71     clean)
72         count=$3
73         [[ -n $count ]] || usage
74         count=$(( $count + 1 ))
75         for snap in $snaps ; do
76             count=$(( $count - 1 ))
77             [[ $count -le 0 ]] || continue
78             zfs destroy -Rv $snap
79         done
80         ;;
81     *)
82         usage
83         ;;
84 esac