#!/usr/bin/env bash set -euo pipefail [ -r "./env-vol_prepare" ] && . ./env-vol_prepare VOL_NAME="${VOL_NAME:?ERROR: VOL_NAME must be set (Hetzner volume name)}" VOL_MOUNT_PATH="${VOL_MOUNT_PATH:?ERROR: VOL_MOUNT_PATH must be set}" VOL_FS_TYPE="${VOL_FS_TYPE:-ext4}" VOL_LABEL_PREFIX="${VOL_LABEL_PREFIX:-scsi-0HC_Volume_}" VOL_FSTAB_OPTIONS="${VOL_FSTAB_OPTIONS:-defaults,nofail,discard 0 0}" DEVICE="/dev/disk/by-id/${VOL_LABEL_PREFIX}${VOL_NAME}" # Hetzner may expose volumes by numeric ID rather than name. # When the name-based path is absent, find the HC volume device by scanning. if [ ! -e "${DEVICE}" ]; then HC_DEVICE=$(ls /dev/disk/by-id/ 2>/dev/null \ | grep "^scsi-0HC_Volume_[0-9]" \ | grep -v "\-part" \ | head -1) if [ -n "${HC_DEVICE}" ]; then DEVICE="/dev/disk/by-id/${HC_DEVICE}" echo "=== vol-prepare: name-based path not found, resolved device: ${DEVICE} ===" fi fi echo "=== vol-prepare: volume=${VOL_NAME}, device=${DEVICE}, mount=${VOL_MOUNT_PATH} ===" if [ ! -e "${DEVICE}" ]; then echo "ERROR: device ${DEVICE} not found." >&2 echo " Hetzner volume '${VOL_NAME}' must be attached to this server before this taskserv runs." >&2 echo " Available block devices by-id:" >&2 ls /dev/disk/by-id/ 2>/dev/null | grep -i hc || echo " (none found)" >&2 exit 1 fi # Format only if the device has no existing filesystem EXISTING_FS="$(blkid -o value -s TYPE "${DEVICE}" 2>/dev/null || echo "")" if [ -z "${EXISTING_FS}" ]; then echo "=== vol-prepare: no filesystem detected — formatting as ${VOL_FS_TYPE} ===" mkfs."${VOL_FS_TYPE}" -F "${DEVICE}" echo "=== vol-prepare: formatted ${DEVICE} as ${VOL_FS_TYPE} ===" else echo "=== vol-prepare: existing filesystem (${EXISTING_FS}) found — skipping format ===" fi # Create mount point mkdir -p "${VOL_MOUNT_PATH}" # Mount if not already mounted if ! mountpoint -q "${VOL_MOUNT_PATH}"; then echo "=== vol-prepare: mounting ${DEVICE} → ${VOL_MOUNT_PATH} ===" mount "${DEVICE}" "${VOL_MOUNT_PATH}" else echo "=== vol-prepare: ${VOL_MOUNT_PATH} already mounted — skipping mount ===" fi # Add to /etc/fstab for persistence across reboots (idempotent) FSTAB_ENTRY="${DEVICE} ${VOL_MOUNT_PATH} ${VOL_FS_TYPE} ${VOL_FSTAB_OPTIONS}" if ! grep -qF "${DEVICE}" /etc/fstab; then echo "=== vol-prepare: adding fstab entry ===" echo "${FSTAB_ENTRY}" >> /etc/fstab else echo "=== vol-prepare: fstab entry already present — skipping ===" fi echo "=== vol-prepare: ready (device=${DEVICE}, mount=${VOL_MOUNT_PATH}, fs=${VOL_FS_TYPE}) ==="