#!/bin/bash

# Start time measurement
start_time=$(date +%s)

# Email settings
EMAIL="david.mccarthy@uoguelph.ca"  # Replace with your email
SUBJECT="Rsync Script Error"

# Function to send error email
send_error_email() {
    echo "Error occurred: $1" | mail -s "$SUBJECT" "$EMAIL"
}

# Error handling
set -e  # Exit on error
trap 'send_error_email "Script failed at line $LINENO"' ERR

echo "This script is located in public_html directory "
date
echo "Conducting IoT - NO IMAGES, NO ZIPS, UPDATE, allowed website dat to come across on 16th jan 2026 --exclude='websitedata.dat'"
rsync -avzh \
    -e "ssh -i /home/bosl/.ssh/rsync_key" \
    --rsync-path=public_html/rsync/rsync \
    --update \
    --exclude='/images/**' \
    --exclude='BOM/**/*.[jJ][pP][gG]' --exclude='BOM/**/*.[jJ][pP][eE][gG]' \
    --exclude='BOM/**/*.[pP][nN][gG]' --exclude='BOM/**/*.[bB][mM][pP]' \
    --exclude='*.[zZ][iI][pP]' \
    --exclude='*.[tT][aA][rR]' \
    --exclude='*.[tT][aA][rR].[gG][zZ]' --exclude='*.[tT][gG][zZ]' \
    --exclude='*.[tT][aA][rR].[bB][zZ]2' --exclude='*.[tT][bB][zZ]2' \
    --exclude='*.[tT][aA][rR].[xX][zZ]' --exclude='*.[tT][xX][zZ]' \
    --exclude='*.7[zZ]' \
    --exclude='*.[rR][aA][rR]' \
    --exclude='*.[gG][zZ]' \
    --exclude='*.[bB][zZ]2' \
    --exclude='*.[xX][zZ]' \
    --exclude='*.[zZ]' \
    --exclude='error_log' \
    --exclude='**/error_log' \
    boslcoma@bosl.com.au:public_html/IoT/ \
    /home/bosl/public_html/IoT/ || send_error_email "IoT rsync failed"

echo "Updating domain references in websitedata.dat files"
find /home/bosl/public_html/IoT/ \
    -path '*/IoT/images' -prune -o \
    -path '*/IoT/BOM' -prune -o \
    -type f -name 'websitedata.dat' -exec sed -i 's|https://www.bosl.com.au|http://203.19.59.2/~bosl|g' {} +
	
	
echo "Conducting Images"
rsync -avzh \
    -e "ssh -i /home/bosl/.ssh/rsync_key" \
    --rsync-path=public_html/rsync/rsync \
    --update \
    boslcoma@bosl.com.au:public_html/IoT/images/ \
    /home/bosl/public_html/IoT/images/ || send_error_email "Images rsync failed"
echo "Conducting DTM - UPDATE ONLY, SLOW"
rsync -avzh \
    -e "ssh -i /home/bosl/.ssh/rsync_key" \
    --rsync-path=public_html/rsync/rsync \
    --update \
    boslcoma@bosl.com.au:public_html/DTM/ \
     /home/bosl/public_html/DTM/ || send_error_email "DTM rsync failed"

echo "Conducting WR - UPDATE ONLY, SLOW"
rsync -avzh \
    -e "ssh -i /home/bosl/.ssh/rsync_key" \
    --rsync-path=public_html/rsync/rsync \
    --update \
    boslcoma@bosl.com.au:public_html/WR/ \
     /home/bosl/public_html/WR/ || send_error_email "WR rsync failed"
	 
chown -R bosl:bosl /home/bosl/public_html/IoT
chown -R bosl:bosl /home/bosl/public_html/DTM
chown -R bosl:bosl /home/bosl/public_html/WR

# Calculate and display total execution time
end_time=$(date +%s)
execution_time=$((end_time - start_time))
echo ""
echo "***"
echo "Total execution time: $execution_time seconds"
echo "***"
echo ""

