#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# Get the directory where the script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Print log function
log() {
    local message="$1"
    local timestamp
    timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] $message"
}

log_file="backup.log"

log_both() {
    local message="$1"
    log "$message"
    log "$message" >> "$log_file"
}

THEME_DIR="stb-theme"

# Check if target theme exists
if [ ! -d "$THEME_DIR" ]; then
    log_both "Error: Target theme directory '$THEME_DIR' not found in $SCRIPT_DIR." >&2
    exit 1
fi

# Generate timestamp and names
DATETIME=$(date +%y-%m-%d_%H-%M)
BACKUP_DIR_NAME="stb-theme-backup_${DATETIME}"
ZIP_NAME="stb-theme-backups_${DATETIME}.zip"

log_both "Starting backup of '$THEME_DIR'..."

# Create temporary directory name matching the target archive structure
TEMP_DIR="$BACKUP_DIR_NAME"

# Trap to ensure cleanup of temporary directory on exit (both normal and abnormal)
cleanup() {
    if [ -d "$TEMP_DIR" ]; then
        log_both "Cleaning up temporary directory..."
        rm -rf "$TEMP_DIR"
    fi
}
trap cleanup EXIT

# Copy the theme to the temporary directory
log_both "Copying files to temporary directory '$TEMP_DIR'..."
cp -r "$THEME_DIR" "$TEMP_DIR"

# Zip the temporary directory
log_both "Creating zip archive '$ZIP_NAME'..."
zip -r "$ZIP_NAME" "$TEMP_DIR" > /dev/null

log_both "Backup completed successfully! Created: $ZIP_NAME"
