Files
gitea-deployment/scripts/setup-swap.sh
2026-03-22 23:06:41 +08:00

66 lines
2.0 KiB
Bash

#!/bin/bash
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
echo -e "${CYAN}--- System Swap Space Check ---${NC}"
SWAP_SIZE=$(free -m | awk '/^Swap:/ {print $2}')
if [ "$SWAP_SIZE" -gt "0" ]; then
echo -e "${GREEN}[OK] Swap space is already configured ($SWAP_SIZE MB). Skipping creation.${NC}"
exit 0
fi
RAM_SIZE=$(free -m | awk '/^Mem:/ {print $2}')
echo -e "${YELLOW}[WARNING] No swap space detected on this server!${NC}"
if [ "$RAM_SIZE" -le "4500" ]; then
echo -e "${RED}[CRITICAL] Your server has ~4GB RAM ($RAM_SIZE MB). A 4GB swap file is HIGHLY recommended.${NC}"
else
echo -e "${CYAN}Your server has plenty of RAM ($RAM_SIZE MB), but adding a swap file is still a safe fallback.${NC}"
fi
echo ""
read -p "Do you want to automatically create a 4GB swap file now? (Requires sudo password) (y/n): " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo -e "${YELLOW}Skipping swap creation. If Gitea crashes, please create swap manually.${NC}"
exit 0
fi
echo -e "${CYAN}Allocating 4GB swap file... This may take a moment.${NC}"
sudo fallocate -l 4G /swapfile
if [ $? -ne 0 ]; then
echo -e "${RED}[ERROR] Failed to allocate space. Your disk might be full.${NC}"
exit 1
fi
echo -e "${CYAN}Securing file permissions...${NC}"
sudo chmod 600 /swapfile
echo -e "${CYAN}Formatting as swap...${NC}"
sudo mkswap /swapfile
echo -e "${CYAN}Enabling swap...${NC}"
sudo swapon /swapfile
if grep -q "/swapfile" /etc/fstab; then
echo -e "${YELLOW}[INFO] /swapfile entry already exists in /etc/fstab.${NC}"
else
echo -e "${CYAN}Adding swap to /etc/fstab to survive reboots...${NC}"
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab > /dev/null
fi
NEW_SWAP=$(free -m | awk '/^Swap:/ {print $2}')
if [ "$NEW_SWAP" -gt "0" ]; then
echo -e "${GREEN}[SUCCESS] 4GB Swap space successfully created and enabled!${NC}"
else
echo -e "${RED}[ERROR] Something went wrong. Swap is still reporting 0 MB.${NC}"
fi