Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 1 | #!/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 | |
| 6 | if [ $# -lt 2 ]; then |
| 7 | echo >&2 "Usage: $0 spec mountpoint [OPTIONS]" |
| 8 | exit 1 |
| 9 | fi |
| 10 | |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 11 | # e.g. /var/volatile/lib |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 12 | spec=$1 |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 13 | |
| 14 | # e.g. /var/lib |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 15 | mountpoint=$2 |
| 16 | |
| 17 | if [ $# -gt 2 ]; then |
| 18 | options=$3 |
| 19 | else |
| 20 | options= |
| 21 | fi |
| 22 | |
| 23 | [ -n "$options" ] && options=",$options" |
| 24 | |
| 25 | mkdir -p "${spec%/*}" |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 26 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 27 | if [ -d "$mountpoint" ]; then |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 28 | |
| 29 | if [ -d "$spec" ]; then |
| 30 | specdir_existed=yes |
| 31 | else |
| 32 | specdir_existed=no |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 33 | mkdir "$spec" |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 34 | 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 Bishop | f3fd288 | 2019-06-21 08:06:37 -0400 | [diff] [blame] | 45 | cp -aPR "$mountpoint"/. "$spec/" |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 46 | fi |
| 47 | |
| 48 | mount -o "bind$options" "$spec" "$mountpoint" |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 49 | fi |
| 50 | elif [ -f "$mountpoint" ]; then |
| 51 | if [ ! -f "$spec" ]; then |
Brad Bishop | f3fd288 | 2019-06-21 08:06:37 -0400 | [diff] [blame] | 52 | cp -aP "$mountpoint" "$spec" |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 53 | fi |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 54 | |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 55 | mount -o "bind$options" "$spec" "$mountpoint" |
| 56 | fi |