]> Sergey Matveev's repositories - dotfiles.git/blob - bin/bin/zsnap.zsh
No gpg-e-fast
[dotfiles.git] / bin / bin / zsnap.zsh
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 EOF
14     exit 1
15 }
16
17 enccmd=(gpg --compress-level 0 --encrypt --recipient offline)
18
19 [[ $# -ge 2 ]] || usage
20
21 what=$1
22 action=$2
23
24 zmodload -F zsh/datetime b:strftime
25 now=$(strftime %Y%m%d%H%M)
26 [[ $what =~ / ]] && depth=1 || depth=${#${(s./.)what}}
27 snaps=$(zfs list -t snap -d $depth -o name -H | grep $what | sort -nr)
28 snaps=(${(f)snaps})
29 latest=${snaps[1]}
30 latest_filename=${latest:gs#/#%}
31
32 case $action in
33     snap-initial)
34         zfs snap -r $what-$now
35         print $what-$now
36         ;;
37     snap)
38         [[ -n $latest ]]
39         [[ "$what-$now" != $latest ]]
40         zfs snap -r $what-$now
41         print $what-$now
42         ;;
43     sync-initial)
44         dst=$3
45         [[ -d $dst ]] || usage
46         setopt PIPE_FAIL
47         zfs send -Rv $latest | zstd | $enccmd > $dst/$latest_filename.zfs.zst.gpg
48         sync
49         touch $dst/$latest_filename.from
50         ;;
51     sync)
52         dst=$3
53         [[ -d $dst ]] || usage
54         latest_dst=($dst/*~$dst/.*(.L0Onn[1]))
55         [[ $latest_dst ]]
56         latest_dst=${latest_dst[1]}
57         latest_dst=${${latest_dst##*/}%.from}
58         [[ $latest_dst != $latest_filename ]]
59         setopt PIPE_FAIL
60         set -x
61         zfs send -Rv -i ${latest_dst:gs#%#/} $latest | zstd | $enccmd > \
62             $dst/$latest_filename.zfs.zst.gpg
63         set +x
64         sync
65         print $latest_dst > $dst/$latest_filename.from
66         ;;
67     clean)
68         count=$3
69         [[ -n $count ]] || usage
70         count=$(( $count + 1 ))
71         for snap in $snaps ; do
72             count=$(( $count - 1 ))
73             [[ $count -le 0 ]] || continue
74             zfs destroy -Rv $snap
75         done
76         ;;
77     *)
78         usage
79         ;;
80 esac