#!/bin/bash
################################################################################
# Script Name: version/3.0.3/UPDATE.sh
# Description: Apply version 3.0.3 migrations: fix crontab syntax for malware scan,
#              restore per-user native cache configurations, and ensure session store
#              TTL settings are up to date.
# Company: hitechcloud.org
# Copyright (c) hitechcloud.org
################################################################################

set -uo pipefail

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
ok()   { echo -e "[3.0.3] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.0.3] ${YELLOW}!${NC} $*" >&2; }

[[ $EUID -eq 0 ]] || { echo "[3.0.3] This update must run as root." >&2; exit 1; }

# 1. Fix crontab syntax if invalid in /etc/cron.d/hitechcloud or /etc/crontab
if [ -f /etc/cron.d/hitechcloud ]; then
    sed -i 's|0 0 \* \* 0 \* \* root /usr/local/hitechcloudcli/hitechcloudcli files-malware_scan|0 0 * * 0 root /usr/local/hitechcloudcli/hitechcloudcli files-malware_scan|g' /etc/cron.d/hitechcloud
    ok "System crontab definitions updated"
fi

# 2. Ensure permissions on native cache scripts
for script in /usr/local/hitechcloudcli/native/varnish.sh /usr/local/hitechcloudcli/native/memcached.sh; do
    if [ -f "$script" ]; then
        chmod +x "$script" 2>/dev/null || true
    fi
done
ok "Native cache and web service scripts verified"

# 3. Reload sentinel and monitor daemon if active
if systemctl is-active --quiet hitechcloud-sentinel 2>/dev/null; then
    systemctl restart hitechcloud-sentinel 2>/dev/null || true
    ok "Sentinel monitoring daemon reloaded"
fi

ok "3.0.3 update steps completed successfully"
exit 0
