Skip to content

Commit 524fbaf

Browse files
logging improved
1 parent 5a50623 commit 524fbaf

File tree

1 file changed

+128
-24
lines changed

1 file changed

+128
-24
lines changed

setup.sh

Lines changed: 128 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,75 @@
55
# This script installs, uninstalls, backs up, restores SystemGuard, and includes load testing using Locust.
66
# Determine the correct user's home directory
77

8+
log() {
9+
# Check if the level is passed; if not, set it to "INFO" as default.
10+
local level="${1:-INFO}"
11+
local message
12+
13+
# Check if a second argument exists, indicating that the first is the level.
14+
if [ -z "$2" ]; then
15+
message="$1" # Only message is passed, assign the first argument to message.
16+
level="INFO" # Default level when only message is passed.
17+
else
18+
message="$2" # When both level and message are passed.
19+
fi
20+
21+
# Define colors based on log levels.
22+
local color_reset="\033[0m"
23+
local color_debug="\033[1;34m" # Blue
24+
local color_info="\033[1;32m" # Green
25+
local color_warning="\033[1;33m" # Yellow
26+
local color_error="\033[1;31m" # Red
27+
local color_critical="\033[1;41m" # Red background
28+
29+
# Select color based on level.
30+
local color="$color_reset"
31+
case "$level" in
32+
DEBUG)
33+
color="$color_debug"
34+
;;
35+
INFO)
36+
color="$color_info"
37+
;;
38+
WARNING)
39+
color="$color_warning"
40+
;;
41+
ERROR)
42+
color="$color_error"
43+
;;
44+
CRITICAL)
45+
color="$color_critical"
46+
;;
47+
*)
48+
color="$color_reset" # Default to no color if the level is unrecognized.
49+
;;
50+
esac
51+
52+
# Log the message with timestamp, level, and message content, applying the selected color.
53+
echo -e "$(date '+%Y-%m-%d %H:%M:%S') ${color}[$level]${color_reset} - $message" | tee -a "$LOG_FILE"
54+
}
55+
56+
set -e
57+
trap 'echo "An error occurred. Exiting..."; exit 1;' ERR
58+
859
# run this script with sudo
960
if [ "$EUID" -ne 0 ]; then
10-
echo "Please run this program with sudo."
61+
log "CRITICAL" "Please run this program with sudo."
1162
exit 1
1263
fi
1364

65+
# function to check for required dependencies
66+
check_dependencies() {
67+
local dependencies=(git curl wget unzip)
68+
for cmd in "${dependencies[@]}"; do
69+
if ! command -v $cmd &> /dev/null; then
70+
log "CRITICAL" "$cmd is required but not installed. Please install it and rerun the script."
71+
exit 1
72+
fi
73+
done
74+
}
75+
check_dependencies
76+
1477
get_user_home() {
1578
if [ -n "$SUDO_USER" ]; then
1679
# When using sudo, SUDO_USER gives the original user who invoked sudo
@@ -44,6 +107,9 @@ LOCUST_FILE="$EXTRACT_DIR/${APP_NAME}-*/src/scripts/locustfile.py"
44107
HOST_URL="http://localhost:5050"
45108
INSTALLER_SCRIPT='setup.sh'
46109

110+
# Number of backups to keep
111+
NUM_OF_BACKUP=5
112+
47113
# Pattern for identifying cron jobs related to SystemGuard
48114
CRON_PATTERN=".systemguard/${APP_NAME}-.*/src/scripts/dashboard.sh"
49115

@@ -58,18 +124,14 @@ ISSUE_URL="$GIT_URL/issues"
58124
create_dir_if_not_exists() {
59125
local dir="$1"
60126
if [ ! -d "$dir" ]; then
61-
mkdir -p "$dir" || { log "Error: Failed to create directory: $dir"; exit 1; }
127+
mkdir -p "$dir" || { log "ERROR" "Failed to create directory: $dir"; exit 1; }
62128
fi
63129
}
64130

65131
create_dir_if_not_exists "$LOG_DIR"
66132
create_dir_if_not_exists "$BACKUP_DIR"
67133

68-
# Logging function with timestamp
69-
log() {
70-
local message="$1"
71-
echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | tee -a "$LOG_FILE"
72-
}
134+
73135

74136
# Check if running with sudo
75137
if [ "$EUID" -eq 0 ]; then
@@ -87,7 +149,7 @@ change_ownership() {
87149
# if permission is set to root then change it to the user
88150
if [ "$(stat -c %U "$directory")" == "root" ]; then
89151
chown -R "$USER_NAME:$USER_NAME" "$directory"
90-
log "Ownership changed from root to $USER_NAME for $directory"
152+
log "INFO" "Ownership changed from root to $USER_NAME for $directory"
91153
fi
92154
fi
93155
}
@@ -105,47 +167,87 @@ add_cron_job() {
105167
# Create log directory with error handling
106168
mkdir -p "$log_dir"
107169
if [ $? -ne 0 ]; then
108-
log "Error: Failed to create log directory: $log_dir"
170+
log "CRITICAL" "Failed to create log directory: $log_dir"
109171
exit 1
110172
fi
111173

112174

113175
# Temporarily store current crontab to avoid overwriting on error
114176
local temp_cron=$(mktemp)
115177
if [ $? -ne 0 ]; then
116-
log "Error: Failed to create temporary file for crontab."
178+
log "CRITICAL "Failed to create temporary file for crontab."
117179
exit 1
118180
fi
119181
120182
# List the current crontab
121183
if ! $crontab_cmd -l 2>/dev/null > "$temp_cron"; then
122-
log "Error: Unable to list current crontab."
184+
log "CRITICAL" "Unable to list current crontab."
123185
rm "$temp_cron"
124186
exit 1
125187
fi
126188
127189
# Ensure the cron job does not already exist
128190
if grep -Fxq "$cron_job" "$temp_cron"; then
129-
log "Cron job already exists: $cron_job"
191+
log "Cron "job already exists: $cron_job"
130192
rm "$temp_cron"
131193
exit 0
132194
fi
133195

134196
# Add the new cron job
135197
echo "$cron_job" >> "$temp_cron"
136198
if ! $crontab_cmd "$temp_cron"; then
137-
log "Error: Failed to add the cron job to crontab."
199+
log "ERROR" "Failed to add the cron job to crontab."
138200
rm "$temp_cron"
139201
exit 1
140202
fi
141203

142204
rm "$temp_cron"
143-
log "Cron job added successfully"
205+
log "INFO" "Cron job added successfully"
144206
log $cron_job
145207
}
146208

209+
# Function to clean up all backups
210+
cleanup_backups() {
211+
log "INFO" "Cleaning up all backups in $BACKUP_DIR..."
212+
213+
# Check if the backup directory exists
214+
if [ -d "$BACKUP_DIR" ]; then
215+
# List all items in the backup directory
216+
local backups=( $(ls -A "$BACKUP_DIR") )
217+
218+
# Check if there are any backups to remove
219+
if [ ${#backups[@]} -gt 0 ]; then
220+
# Loop through each item and remove it
221+
for backup in "${backups[@]}"; do
222+
rm -rf "$BACKUP_DIR/$backup"
223+
log "INFO" "Removed backup: $backup"
224+
done
225+
log "INFO" "All backups have been cleaned up."
226+
else
227+
log "INFO" "No backups found to clean up."
228+
fi
229+
else
230+
log "ERROR" "Backup directory $BACKUP_DIR does not exist."
231+
fi
232+
}
233+
234+
235+
rotate_backups() {
236+
local num_of_backup=$1
237+
log "INFO" "Rotating backups... Keeping last $num_of_backup backups."
238+
local backups=( $(ls -t $BACKUP_DIR) )
239+
local count=${#backups[@]}
240+
if [ "$count" -gt "$num_of_backup" ]; then
241+
local to_remove=( "${backups[@]:$num_of_backup}" )
242+
for backup in "${to_remove[@]}"; do
243+
rm -rf "$BACKUP_DIR/$backup"
244+
log "INFO" "Removed old backup: $backup"
245+
done
246+
fi
247+
}
147248
# Backup function for existing configurations
148249
backup_configs() {
250+
rotate_backups $NUM_OF_BACKUP
149251
log "Backing up existing configurations..."
150252
if [ -d "$EXTRACT_DIR" ]; then
151253
mkdir -p "$BACKUP_DIR"
@@ -176,7 +278,7 @@ restore() {
176278
echo "Are you sure you want to restore this backup? This will overwrite the current installation. (y/n)"
177279
read CONFIRM
178280
if [ "$CONFIRM" != "y" ]; then
179-
log "Restore aborted by user."
281+
log "WARNING" "Restore aborted by user."
180282
exit 0
181283
fi
182284

@@ -190,8 +292,7 @@ restore() {
190292
cp -r "$BACKUP" "$EXTRACT_DIR"
191293
log "Restore completed from backup: $BACKUP"
192294
else
193-
log "No backups found to restore."
194-
echo "No backups found in $BACKUP_DIR."
295+
log "WARNING" "No backups found to restore."
195296
fi
196297
}
197298

@@ -207,7 +308,7 @@ install_executable() {
207308
cp "$CURRENT_SCRIPT" "$EXECUTABLE"
208309
log "Executable installed successfully."
209310
else
210-
log "Error: Script file not found. Cannot copy to /usr/local/bin."
311+
log "ERROR" "Script file not found. Cannot copy to /usr/local/bin."
211312
fi
212313
}
213314

@@ -233,7 +334,7 @@ fetch_latest_version() {
233334
log "Fetching the latest version of $APP_NAME from GitHub..."
234335
VERSION=$(curl -s https://api.github.com/repos/$GIT_USER/$GIT_REPO/releases/latest | grep -Po '"tag_name": "\K.*?(?=")')
235336
if [ -z "$VERSION" ]; then
236-
log "Error: Unable to fetch the latest version. Please try again or specify a version manually."
337+
log "ERROR" "Unable to fetch the latest version. Please try again or specify a version manually."
237338
exit 1
238339
fi
239340
log "Latest version found: $VERSION"
@@ -245,7 +346,7 @@ download_release() {
245346
local output=$2
246347
log "Downloading $APP_NAME from $url..."
247348
if ! wget -q "$url" -O "$output"; then
248-
log "Error: Failed to download $APP_NAME. Please check the URL and try again."
349+
log "ERROR" "Failed to download $APP_NAME. Please check the URL and try again."
249350
exit 1
250351
fi
251352
log "Download completed successfully."
@@ -258,7 +359,7 @@ setup_cron_job() {
258359
if $crontab_cmd -l | grep -q "$CRON_PATTERN"; then
259360
log "Cron job added successfully."
260361
else
261-
log "Error: Failed to add the cron job."
362+
log "ERROR" "Failed to add the cron job."
262363
exit 1
263364
fi
264365
}
@@ -295,7 +396,7 @@ install_from_git() {
295396
log "Selected branch: $BRANCH."
296397
;;
297398
*) # Invalid input handling
298-
log "Invalid selection. Please enter '1' for Stable, '2' for Development, or '3' to specify a branch."
399+
log "WARNING" "Invalid selection. Please enter '1' for Stable, '2' for Development, or '3' to specify a branch."
299400
exit 1
300401
;;
301402
esac
@@ -305,15 +406,15 @@ install_from_git() {
305406

306407
log "Cloning the $APP_NAME repository from GitHub..."
307408
if ! git clone $FULL_GIT_URL "$GIT_INSTALL_DIR"; then
308-
log "Error: Failed to clone the repository. Please check your internet connection and the branch name, and try again."
409+
log "ERROR" "Failed to clone the repository. Please check your internet connection and the branch name, and try again."
309410
exit 1
310411
fi
311412

312413
log "Repository cloned successfully."
313414

314415
# Change to the installation directory
315416
cd "$GIT_INSTALL_DIR" || {
316-
log "Error: Failed to navigate to the installation directory.";
417+
log "ERROR" "Failed to navigate to the installation directory.";
317418
exit 1;
318419
}
319420

@@ -468,6 +569,7 @@ show_help() {
468569
echo " --load-test Start Locust load testing"
469570
echo " --status Check the status of $APP_NAME installation"
470571
echo " --health-check Perform a health check on localhost:5005"
572+
echo " --clean-backups Clean up all backups"
471573
echo " --help Display this help message"
472574
}
473575

@@ -480,6 +582,7 @@ for arg in "$@"; do
480582
--load-test) ACTION="load_test" ;;
481583
--status) ACTION="check_status" ;;
482584
--health-check) ACTION="health_check" ;;
585+
--clean-backups) ACTION="cleanup_backups" ;;
483586
--help) show_help; exit 0 ;;
484587
*) echo "Unknown option: $arg"; show_help; exit 1 ;;
485588
esac
@@ -494,6 +597,7 @@ case $ACTION in
494597
install_latest) install_latest ;;
495598
check_status) check_status ;;
496599
health_check) health_check ;;
600+
cleanup_backups) cleanup_backups ;;
497601
*) echo "No action specified. Use --help for usage information." ;;
498602
esac
499603
# # End of script

0 commit comments

Comments
 (0)