user-data/ripcord/ripcord.sh
2025-07-06 07:14:19 +00:00

79 lines
No EOL
2.6 KiB
Bash

#!/bin/sh
# ==============================================================================
# Ripcord - Your server's last-ditch emergency disk space release.
#
# This script runs once on first boot to create a large "ballast" file.
# Deleting this file in an emergency frees up critical disk space.
# The data is from /dev/urandom to ensure it is not compressible by ZFS/lz4.
# ==============================================================================
# --- Configuration ---
# Percentage of the total root filesystem size to use for the emergency file.
PERCENTAGE=5
# The emergency file. The name itself is the instruction.
# It contains the project name for easy identification.
TARGET_FILE="/RIPCORD_EMERGENCY_DELETE_FOR_DISK_SPACE.dat"
# A flag file to ensure this script only ever runs once.
FLAG_FILE="/var/log/ripcord-deployed.flag"
# --- Script Logic ---
# Function to log messages with a timestamp
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}
# 1. Check if Ripcord has already been deployed
if [ -f "$FLAG_FILE" ]; then
log "Ripcord has already been deployed. Exiting."
exit 0
fi
log "--- Deploying Ripcord ---"
# 2. Create the emergency ballast file
if [ -f "$TARGET_FILE" ]; then
log "Warning: Ripcord target file '$TARGET_FILE' already exists. Skipping creation."
else
log "Preparing to create Ripcord ballast file at '$TARGET_FILE'."
# Get total size of '/' in Kilobytes using the POSIX standard format.
total_kb=$(df -Pk / | tail -1 | awk '{print $2}')
if [ -z "$total_kb" ]; then
log "Error: Could not determine total disk size for '/'."
exit 1
fi
log "Total size of root filesystem: ${total_kb} KB."
# Calculate the target file size in Kilobytes.
target_size_kb=$(( (total_kb * PERCENTAGE) / 100 ))
log "Target ballast file size will be ${PERCENTAGE}% of total: ${target_size_kb} KB."
# Use dd to create the file from /dev/urandom.
# This data is uncompressible, which is critical for filesystems like ZFS.
log "Creating file from /dev/urandom... This may take a significant amount of time."
dd if=/dev/urandom of="$TARGET_FILE" bs=1024 count="$target_size_kb" status=none 2>/dev/null
if [ $? -eq 0 ]; then
log "Successfully created '$TARGET_FILE'."
else
log "Error: dd command failed to create '$TARGET_FILE'."
rm -f "$TARGET_FILE" # Clean up partial file on failure
exit 1
fi
fi
# 3. Create the flag file to prevent this script from running again
log "Creating deployment flag at '$FLAG_FILE'."
touch "$FLAG_FILE"
log "--- Ripcord deployment complete ---"
exit 0