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