blob: e32e675308ca0669034801829f88de697ef53dd4 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#!/bin/sh
2#
3# Perform a bind mount, copying existing files as we do so to ensure the
4# overlaid path has the necessary content.
5
6if [ $# -lt 2 ]; then
7 echo >&2 "Usage: $0 spec mountpoint [OPTIONS]"
8 exit 1
9fi
10
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080011# e.g. /var/volatile/lib
Patrick Williamsc124f4f2015-09-15 14:41:29 -050012spec=$1
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080013
14# e.g. /var/lib
Patrick Williamsc124f4f2015-09-15 14:41:29 -050015mountpoint=$2
16
17if [ $# -gt 2 ]; then
18 options=$3
19else
20 options=
21fi
22
23[ -n "$options" ] && options=",$options"
24
25mkdir -p "${spec%/*}"
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080026
Patrick Williamsc124f4f2015-09-15 14:41:29 -050027if [ -d "$mountpoint" ]; then
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080028
29 if [ -d "$spec" ]; then
30 specdir_existed=yes
31 else
32 specdir_existed=no
Patrick Williamsc124f4f2015-09-15 14:41:29 -050033 mkdir "$spec"
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080034 fi
35
36 # Fast version of calculating `dirname ${spec}`/.`basename ${spec}`-work
37 overlay_workdir="${spec%/*}/.${spec##*/}-work"
38 mkdir "${overlay_workdir}"
39
40 # Try to mount using overlay, which is must faster than copying files.
41 # If that fails, fall back to slower copy.
42 if ! mount -t overlay overlay -olowerdir="$mountpoint",upperdir="$spec",workdir="$overlay_workdir" "$mountpoint" > /dev/null 2>&1; then
43
44 if [ "$specdir_existed" != "yes" ]; then
Brad Bishopf3fd2882019-06-21 08:06:37 -040045 cp -aPR "$mountpoint"/. "$spec/"
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080046 fi
47
48 mount -o "bind$options" "$spec" "$mountpoint"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050049 fi
50elif [ -f "$mountpoint" ]; then
51 if [ ! -f "$spec" ]; then
Brad Bishopf3fd2882019-06-21 08:06:37 -040052 cp -aP "$mountpoint" "$spec"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050053 fi
Patrick Williamsc124f4f2015-09-15 14:41:29 -050054
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080055 mount -o "bind$options" "$spec" "$mountpoint"
56fi