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