mgm-image/entrypoint.sh
Adam Štrauch 12c970cd9f
All checks were successful
Build a dev image / build (push) Successful in 15s
Don't generate keys twice
2025-10-07 23:34:06 +02:00

90 lines
2.3 KiB
Bash

#!/bin/bash
# Entrypoint script to start SSH and ttyd services
set -e
if [ -z "$TTYD_TOKEN" ]; then
echo "Warning: TTYD_TOKEN not set, exiting."
exit 1
fi
if [ -z "$SET_SHELL" ]; then
echo "Warning: SET_SHELL not set, using default '/bin/bash'."
export SET_SHELL="/bin/bash"
fi
echo "Initializing services..."
# Generate SSH host keys if they don't exist
if [ ! -f /etc/ssh/ssh_host_rsa_key ]; then
echo "Generating SSH host keys..."
ssh-keygen -A
fi
if [ -f /etc/ssh/sshd_config -a `cat /etc/ssh/sshd_config | wc -l` = 1 ]; then
echo "sshd_config is not complete, regenerating..."
rm -f /etc/ssh/sshd_config
fi
if [ ! -f /etc/ssh/sshd_config ]; then
echo "Include /etc/ssh/sshd_config.d/*.conf" > /etc/ssh/sshd_config
echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
echo "AuthorizedKeysFile .ssh/authorized_keys" >> /etc/ssh/sshd_config
echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config
echo "AllowTcpForwarding no" >> /etc/ssh/sshd_config
echo "GatewayPorts no" >> /etc/ssh/sshd_config
echo "X11Forwarding no" >> /etc/ssh/sshd_config
echo "Subsystem sftp internal-sftp" >> /etc/ssh/sshd_config
fi
# Array to store child PIDs
declare -a CHILD_PIDS=()
# Function to handle shutdown gracefully
shutdown_handler() {
echo "Shutting down services..."
# Send SIGTERM to all child processes
for pid in "${CHILD_PIDS[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
echo "Sending SIGTERM to PID: $pid"
kill -TERM "$pid" 2>/dev/null || true
fi
done
# Wait a bit for graceful shutdown
sleep 2
# Force kill any remaining processes
for pid in "${CHILD_PIDS[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
echo "Force killing PID: $pid"
kill -KILL "$pid" 2>/dev/null || true
fi
done
echo "All services stopped"
exit 0
}
# Set up signal handlers
trap shutdown_handler SIGTERM SIGINT
# Start services in background and collect PIDs
echo "Starting services..."
echo "Starting SSH service..."
/app/service.ssh.sh &
CHILD_PIDS+=($!)
echo "SSH service started with PID: $!"
echo "Starting ttyd service..."
/app/service.ttyd.sh &
CHILD_PIDS+=($!)
echo "ttyd service started with PID: $!"
echo "Both services are running. PIDs: ${CHILD_PIDS[*]}"
# Wait for all background processes
wait