blob: e32e675308ca0669034801829f88de697ef53dd4 [file] [log] [blame]
xf.li86118912025-03-19 20:07:27 -07001#!/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
11# e.g. /var/volatile/lib
12spec=$1
13
14# e.g. /var/lib
15mountpoint=$2
16
17if [ $# -gt 2 ]; then
18 options=$3
19else
20 options=
21fi
22
23[ -n "$options" ] && options=",$options"
24
25mkdir -p "${spec%/*}"
26
27if [ -d "$mountpoint" ]; then
28
29 if [ -d "$spec" ]; then
30 specdir_existed=yes
31 else
32 specdir_existed=no
33 mkdir "$spec"
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
45 cp -aPR "$mountpoint"/. "$spec/"
46 fi
47
48 mount -o "bind$options" "$spec" "$mountpoint"
49 fi
50elif [ -f "$mountpoint" ]; then
51 if [ ! -f "$spec" ]; then
52 cp -aP "$mountpoint" "$spec"
53 fi
54
55 mount -o "bind$options" "$spec" "$mountpoint"
56fi