]> Sergey Matveev's repositories - dotfiles.git/blob - bin/bin/zsnap.zsh
I learn zsh
[dotfiles.git] / bin / bin / zsnap.zsh
1 #!/usr/bin/env zsh
2
3 set -e
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 EOF
13     exit 1
14 }
15
16 enccmd="gpg --compress-level 0 --encrypt --recipient offline --cipher-algo AES-128"
17
18 [[ $# -ge 2 ]] || usage
19
20 what=$1
21 action=$2
22
23 now=$(date "+%Y%m%d%H%M")
24 depth=${#${(s./.)what}}
25 snaps=$(zfs list -t snap -d $depth -o name -H | grep $what | sort -nr)
26 snaps=(${(f)snaps})
27 latest=${snaps[1]}
28 latest_filename=${latest:gs#/#%}
29
30 case $action in
31     snap-initial)
32         zfs snap -r $what-$now
33         print $what-$now
34         ;;
35     snap)
36         [[ -n $latest ]]
37         [[ "$what-$now" != $latest ]]
38         zfs snap -r $what-$now
39         print $what-$now
40         ;;
41     sync-initial)
42         dst=$3
43         [[ -d $dst ]] || usage
44         setopt PIPE_FAIL
45         zfs send -Rv $latest | zstd | ${=enccmd} > \
46             $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/*(.Onn[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         zfs send -Rv -i ${latest_dst:gs#%#/} $latest | zstd | ${=enccmd} > \
60             $dst/$latest_filename.zfs.zst.gpg
61         sync
62         print $latest_dst > $dst/$latest_filename.from
63         ;;
64     clean)
65         count=$3
66         [[ -n $count ]] || usage
67         count=$(( $count + 1 ))
68         for snap in $snaps ; do
69             count=$(( $count - 1 ))
70             [[ $count -le 0 ]] || continue
71             zfs destroy -Rv $snap
72         done
73         ;;
74     *)
75         usage
76         ;;
77 esac