summaryrefslogtreecommitdiff
path: root/snap.sh
blob: 36f32e62f99d9e01f0d823ca7fc46b91aee5fbd7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/bin/sh -euf

MOUNT_DIRECTORY="/var/backups/dataset-snapshots"
SNAPSHOT_LABEL="snap"

usage() (
	echo "snap.sh <snap|free> <dataset>"
	echo
	echo "Creates or destroys a snapshot of a ZFS dataset, labelled with @$SNAPSHOT_LABEL."
	echo "Snapshots are automatically mounted in $MOUNT_DIRECTORY."
	echo "If a snapshot already exists, it is replaced."
	echo
)

create_snapshot() (
	DATASET="$1"

	SNAPSHOT_NAME="$DATASET@$SNAPSHOT_LABEL"
	SNAPSHOT_DIRECTORY="$MOUNT_DIRECTORY/$DATASET"

	if zfs list "$SNAPSHOT_NAME" >/dev/null 2>/dev/null; then
		echo "Snapshot already exists. Overwriting."
		destroy_snapshot "$DATASET"
	fi

	zfs snapshot "$SNAPSHOT_NAME"
	mkdir -p "$SNAPSHOT_DIRECTORY"
	mount -t zfs "$SNAPSHOT_NAME" "$SNAPSHOT_DIRECTORY"
)

destroy_snapshot() (
	DATASET="$1"

	SNAPSHOT_NAME="$DATASET@$SNAPSHOT_LABEL"

	umount "$SNAPSHOT_NAME" 2>/dev/null || true
	zfs destroy "$SNAPSHOT_NAME"
)

case "${1:-help}" in
	"help")	usage;;
	"snap")	create_snapshot "$2";;
	"free")	destroy_snapshot "$2";;
esac