#!/usr/bin/env bash
set -euo pipefail

# Install rclone for backup uploads and migrate upload worker from cron to systemd daemon

# Resolve the release root directory (this script is at scripts/updates/<version>/install-upload-daemon.sh)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RELEASE_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

echo "Installing rclone backup upload system..."

# Install rclone if not present
if ! command -v rclone &>/dev/null; then
    echo "Installing rclone..."
    curl -sL https://rclone.org/install.sh | bash
    if command -v rclone &>/dev/null; then
        echo "rclone $(rclone version --check 2>/dev/null | head -1 || echo 'installed') successfully"
    else
        echo "WARNING: rclone installation failed - uploads will use PHP fallback"
    fi
else
    echo "rclone already installed: $(rclone version 2>/dev/null | head -1 || echo 'unknown version')"
fi

# Install systemd unit file
echo "Installing backup upload systemd service..."
cp "$RELEASE_ROOT/configs/whp-backup-upload.service" /etc/systemd/system/
chmod 644 /etc/systemd/system/whp-backup-upload.service
systemctl daemon-reload
systemctl enable whp-backup-upload.service

# Ensure log file exists
touch /var/log/whp-backup.log
chmod 640 /var/log/whp-backup.log

# Remove old cron entry for upload worker (both possible paths)
echo "Removing old upload worker cron entry..."
crontab -l 2>/dev/null | grep -v 'backup-upload-worker.php' | crontab - || true

# Start the service
systemctl start whp-backup-upload.service

echo "Backup upload daemon installed and started"
echo "  - Service: systemctl status whp-backup-upload"
echo "  - Logs: /var/log/whp-backup.log"

exit 0
