#!/bin/bash
# 🚀 VPS Setup Script for Osmium Tool
# Installs osmium-tool on Debian/Ubuntu based systems.

set -euo pipefail

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

log "Starting Osmium-Tool installation..."

# 1. Update package list
log "Updating apt package list..."
sudo apt-get update -y

# 2. Install dependencies for Osmium
log "Installing Osmium build dependencies..."
sudo apt-get install -y build-essential libprotozero-dev libprotobuf-dev protobuf-compiler libboost-dev libbz2-dev libexpat-dev libgdal-dev libgeos-dev lua5.3 liblua5.3-dev libsparsehash-dev zlib1g-dev libgdal-dev libxml2-dev

# 3. Install Osmium Tool via source (more reliable for specific versions/platforms)
# Or just use pre-built if available. Pre-built is faster.
# Check for official PPA
if sudo add-apt-repository --yes ppa:osm-kumi/osmium && sudo apt-get update; then
    log "Installing osmium-tool from PPA..."
    sudo apt-get install -y osmium-tool
else
    log "PPA not available or failed, falling back to manual build from source."
    OSMIUM_VERSION="1.17.1" # Latest stable version at the time
    log "Downloading Osmium Tool v${OSMIUM_VERSION} source..."
    wget -q https://github.com/osmcode/osmium-tool/archive/v${OSMIUM_VERSION}.tar.gz -O /tmp/osmium-tool.tar.gz
    
    log "Extracting source..."
    mkdir -p /tmp/osmium-tool-build
    tar -xzf /tmp/osmium-tool.tar.gz -C /tmp/osmium-tool-build --strip-components 1
    
    log "Building Osmium Tool (this might take a while)..."
    cd /tmp/osmium-tool-build
    ./autogen.sh
    ./configure
    make
    sudo make install
    
    log "Cleaning up build files..."
    rm -rf /tmp/osmium-tool-build /tmp/osmium-tool.tar.gz
fi

# 4. Verify installation
if command -v osmium &> /dev/null; then
    log "✅ Osmium-Tool installed successfully: $(osmium --version)"
else
    log "❌ Osmium-Tool installation FAILED."
    exit 1
fi

log "Osmium-Tool setup script finished."
