Files
backup-scripts/create-systemd-service-and-timer.sh

88 lines
2.3 KiB
Bash
Executable File

#!/bin/bash
if [ "$EUID" -ne 0 ]; then
echo "Please run as root"
exit
fi
if [ $# -gt 1 ]; then
echo "Usage: create-systemd-service-and-timer.sh [--fast]"
echo ""
echo "options:"
echo "--fast sets the backup script, log file and directory based on the name of the service"
echo ""
exit 0
fi
echo "Please enter the desired name for the service (e.g., backup). Can only contain [a-z, A-Z, 0-9]: "
read SERVICE_NAME
BAKUP_SCRIPT_PATH=""
LOG_FILE_PATH=""
WORKING_DIRECTORY=""
if [ "$1" = "--fast" ]; then
echo "Enter the name of the user where the service directory lives:"
read USER_NAME
BACKUP_SCRIPT_PATH="/home/$USER_NAME/$SERVICE_NAME/backup-$SERVICE_NAME.sh"
LOG_FILE_PATH="/home/$USER_NAME/$SERVICE_NAME/backup-$SERVICE_NAME.log"
WORKING_DIRECTORY="/home/$USER_NAME/$SERVICE_NAME"
else
echo "Please enter the path to your backup script (e.g., /home/user/service/backup.sh): "
read BACKUP_SCRIPT_PATH
echo "Please enter the path to the log file for the script (e.g., /home/sem/service/backup.log): "
read LOG_FILE_PATH
echo "Please enter the working directory for the backup service (e.g., /home/user/service): "
read WORKING_DIRECTORY
fi
echo "Using service name: $SERVICE_NAME"
echo "Using backup script path: $BACKUP_SCRIPT_PATH"
echo "Using log file path: $LOG_FILE_PATH"
echo "Using service working directory: $WORKING_DIRECTORY"
echo "Please enter the desired OnCalendar time for the timer (e.g.'Mon *-*-* 02:00:00'): "
read ONCALENDAR_TIME
echo "Please enter a description for the interval of the timer (e.g., 'Monday at 02:00'): "
read TIMER_DESCRIPTION
SERVICE_FILE="/etc/systemd/system/backup-${SERVICE_NAME}.service"
TIMER_FILE="/etc/systemd/system/backup-${SERVICE_NAME}.timer"
cat > $SERVICE_FILE <<EOL
[Unit]
Description=Backup $SERVICE_NAME to the backups VM
[Service]
Type=oneshot
ExecStart=$BACKUP_SCRIPT_PATH > $LOG_FILE_PATH
User=sem
WorkingDirectory=$WORKING_DIRECTORY
EOL
echo "Created service file at $SERVICE_FILE"
cat > $TIMER_FILE <<EOL
[Unit]
Description=Backup $SERVICE_NAME every $TIMER_DESCRIPTION
[Timer]
OnCalendar=$ONCALENDAR_TIME
Persistent=true
[Install]
WantedBy=timers.target
EOL
echo "Created timer file at $TIMER_FILE"
systemctl daemon-reload
systemctl enable backup-${SERVICE_NAME}.timer
systemctl start backup-${SERVICE_NAME}.timer
systemctl list-timers