Files
ubuntu/scripts/entrypoint.sh

101 lines
2.8 KiB
Bash
Executable File

#!/usr/bin/env bash
if [[ "$UPDATE_APT" == "1" || "${UPDATE_APT,,}" == "true" ]]; then
# Gracefully update package lists if network is available
echo "Checking network connectivity..."
if ping -c 1 -W 5 8.8.8.8 >/dev/null 2>&1 || ping -c 1 -W 5 1.1.1.1 >/dev/null 2>&1; then
echo "Network detected, refreshing package lists..."
if sudo apt update; then
echo "Package lists updated successfully"
else
echo "Warning: apt update failed despite network connectivity"
echo "Falling back to cached package lists"
fi
else
echo "No network connectivity detected, using cached package lists"
fi
fi
# Global variable to track background processes
TAIL_PID=""
term_handler() {
echo "Received termination signal, cleaning up..."
# Kill the tail process if it's running
if [[ -n "$TAIL_PID" ]]; then
kill "$TAIL_PID" 2>/dev/null
fi
# Run user-defined exit commands
# First run the legacy COMMAND_EXIT for backward compatibility
if [[ -n "$COMMAND_EXIT" ]]; then
eval "$COMMAND_EXIT"
fi
# Then run numbered COMMAND_EXIT variables in order
for i in {01..99}; do
var_name="COMMAND_EXIT$i"
var_value="${!var_name}"
if [[ -n "$var_value" ]]; then
echo "Running $var_name..."
eval "$var_value"
fi
done
echo "Cleanup completed, exiting..."
exit 0
}
# Setup signal handlers for graceful shutdown
trap 'term_handler' SIGTERM SIGINT
# setup home directory for the current user. It is useful for attaching vscode with container.
user_name=$(whoami)
user_home="/home/$user_name"
sudo mkdir -p "$user_home"
sudo chown -R "$(id -u):$(id -g)" "$user_home"
cp -r /etc/skel/. "$user_home" 2>/dev/null || true
if [[ $LOG_FILE != "/dev/null" ]]; then
sudo touch "$LOG_FILE"
sudo chown -R "$(id -u):$(id -g)" "$LOG_FILE"
fi
echo "Starting SSH service..."
sudo service ssh start
# Run initialization commands
# First run the legacy COMMAND_INIT for backward compatibility
if [[ -n "$COMMAND_INIT" ]]; then
eval "$COMMAND_INIT"
fi
# Then run numbered COMMAND_INIT variables in order
for i in {01..99}; do
var_name="COMMAND_INIT$i"
var_value="${!var_name}"
if [[ -n "$var_value" ]]; then
echo "Running $var_name..."
eval "$var_value"
fi
done
# Start the main process loop
if [[ $LOG_FILE == "/dev/null" ]]; then
# If no log file, just wait for signals
echo "Container ready, waiting for signals..."
while true; do
sleep 1 &
wait $!
done
else
# If log file specified, tail it
echo "Container ready, tailing log file: $LOG_FILE"
tail -f "$LOG_FILE" &
TAIL_PID=$!
# Wait for the tail process or signals
wait $TAIL_PID
fi