#!/bin/bash
set -e

# Configuration
REMOTE_URL="https://fgtest.moneroatm.xyz/ticket-machine/envoy-logger"
TEMP_DIR="/tmp/envoy-logger-install"

echo "=== Envoy Logger Remote Installer ==="
echo

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "Error: This script must be run as root"
    echo "Please run: sudo $0"
    exit 1
fi

# Check for wget
if ! command -v wget &> /dev/null; then
    echo "Error: wget is not installed"
    echo "Install it with: sudo pacman -S wget"
    exit 1
fi

# Create temporary directory
echo "Creating temporary directory..."
rm -rf "$TEMP_DIR"
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"

# Download files
echo "Downloading files from ${REMOTE_URL}..."
wget -q --show-progress "${REMOTE_URL}/main.py"
wget -q --show-progress "${REMOTE_URL}/dispenser_action.py"
wget -q --show-progress "${REMOTE_URL}/f53_errors.py"
wget -q --show-progress "${REMOTE_URL}/install-service.sh"
wget -q --show-progress "${REMOTE_URL}/pyproject.toml" || true

echo "Download complete!"
echo

# Make install script executable
chmod +x install-service.sh

# Run the installer
echo "Running installer..."
./install-service.sh

# Cleanup
echo
echo "Cleaning up temporary files..."
cd /
rm -rf "$TEMP_DIR"

echo "Installation complete!"
