scripts

Random scripts
git clone git://git.margiolis.net/scripts.git
Log | Files | Refs | README | LICENSE

backup (1537B)


      1 #!/bin/sh
      2 
      3 main()
      4 {
      5 	f_incr=0	# Incremental backup
      6 	f_snap=0	# Renew snapshots in case they already exist
      7 
      8 	while getopts "ir" arg; do
      9 	case "${arg}" in
     10 		i) f_incr=1 ;;
     11 		r) f_snap=1 ;;
     12 		*) usage ;;
     13 	esac
     14 	done
     15 	shift $((OPTIND - 1))
     16 
     17 	test ${#} -ne 2 && usage
     18 
     19 	src_pool="${1}"
     20 	dst_pool="${2}"
     21 
     22 	pool_exists "${src_pool}"
     23 	pool_exists "${dst_pool}"
     24 
     25 	new_snap="$(date '+%Y%m%d')"
     26 	src_last_snap=$(last_snap "${src_pool}")
     27 	dst_last_snap=$(last_snap "${dst_pool}")
     28 	nsnaps=$(zfs list -t snapshot -o name ${dst_pool} | sed 1d | wc -l)
     29 
     30 	delete_existing_snap "${dst_pool}" "${dst_last_snap}"
     31 	zfs snapshot -r ${src_pool}@${new_snap}
     32 
     33 	if [ ${f_incr} -eq 1 ]; then
     34 		zfs send -RI ${src_pool}@${dst_last_snap} ${src_pool}@${new_snap} |
     35 		pv | zfs recv -Fu ${dst_pool}
     36 	else
     37 		zfs send -R ${src_pool}@${new_snap} | pv | zfs recv -Fu ${dst_pool}
     38 	fi
     39 }
     40 
     41 usage()
     42 {
     43 	echo "usage: ${0##*/} [-ir] src[/set] dst[/set]" 1>&2
     44 	exit 1
     45 }
     46 
     47 err()
     48 {
     49 	echo "${0##*/}: ${@}" 1>&2
     50 	exit 1
     51 }
     52 
     53 pool_exists()
     54 {
     55 	local foo=$(zfs list -o name | sed 1d | grep -x "${1}")
     56 
     57 	test -z "${foo}" && err "pool ${1} does not exist"
     58 }
     59 
     60 last_snap()
     61 {
     62 	zfs list -t snapshot -o name "${1}" | cut -f2 -d'@' | tail -1
     63 }
     64 
     65 # Make appropriate checks before creating new snapshot.
     66 # If the snapshot already exists, either renew it or exit.
     67 delete_existing_snap()
     68 {
     69 	local pool=${1}
     70 	local last_snap=${2}
     71 
     72 	if [ "${last_snap}" = "${new_snap}" ]; then
     73 		test ${f_snap} -eq 1 || err "snapshot ${pool}@${new_snap} exists already"
     74 		zfs destroy -r ${pool}@${new_snap}
     75 	fi
     76 }
     77 
     78 main ${@}