Add bindmounts.sh

This commit is contained in:
HHF Technology 2024-12-08 08:33:33 +05:30
parent 03a7b6cd60
commit b9de0b8950

105
bindmounts.sh Normal file
View file

@ -0,0 +1,105 @@
#!/usr/bin/env bash
CONFIG_FILE="/etc/proxmox-bindmounts.conf"
# Function to create config file
create_config() {
echo "First run detected. Setting up configuration..."
read -p "Enter mount source path (e.g., /z/media): " MNT_SOURCE
read -p "Enter mount target path (e.g., /media): " MNT_TARGET
read -p "Enter container base path (e.g., /z/pve): " CT_BASE
read -p "Enter container IDs (space-separated): " -a CT_IDS
# Save to config file
cat > "$CONFIG_FILE" << EOF
MNT_SOURCE="$MNT_SOURCE"
MNT_TARGET="$MNT_TARGET"
CT_BASE="$CT_BASE"
CT_IDS=(${CT_IDS[@]})
EOF
chmod 600 "$CONFIG_FILE"
echo "Configuration saved to $CONFIG_FILE"
}
# Check if config exists, if not create it
if [ ! -f "$CONFIG_FILE" ]; then
create_config
fi
# Source the config file
source "$CONFIG_FILE"
# Set signal traps
trap "exit 1" INT TERM KILL
trap "exit 0" QUIT HUP
# Function to validate paths
validate_paths() {
if [ ! -d "$MNT_SOURCE" ]; then
echo "Error: Source directory $MNT_SOURCE does not exist!"
exit 1
fi
if [ ! -d "$CT_BASE" ]; then
echo "Error: Container base directory $CT_BASE does not exist!"
exit 1
fi
}
# Function to mount
mount_containers() {
for ID in "${CT_IDS[@]}"; do
TARGET_PATH="${CT_BASE}/subvol-${ID}-disk-1${MNT_TARGET}"
# Try unmounting first
if mountpoint -q "$TARGET_PATH"; then
umount -v "$TARGET_PATH" && rm -rf "${TARGET_PATH:?}"/*
fi
# Create target directory if needed
mkdir -p "$TARGET_PATH"
# Perform the bind mount
mount -v -o bind "$MNT_SOURCE" "$TARGET_PATH"
if [ $? -eq 0 ]; then
echo "Successfully mounted for container $ID"
else
echo "Failed to mount for container $ID"
fi
done
}
# Function to unmount
unmount_containers() {
for ID in "${CT_IDS[@]}"; do
TARGET_PATH="${CT_BASE}/subvol-${ID}-disk-1${MNT_TARGET}"
if mountpoint -q "$TARGET_PATH"; then
umount -v "$TARGET_PATH"
fi
done
}
# Main logic
case "$1" in
up)
validate_paths
mount_containers
# Keep service running for systemd
exec /bin/sleep infinity
;;
down)
unmount_containers
;;
reconfigure)
create_config
;;
*)
echo "Usage: $0 {up|down|reconfigure}"
echo " up - Mount all containers"
echo " down - Unmount all containers"
echo " reconfigure - Reset configuration"
exit 1
;;
esac