#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

REPO_SRC="$PROJECT_ROOT/repo/src"
REPO_REQS="$PROJECT_ROOT/repo/src/requirements.txt"

INSTALL_DIR="/usr/share/calculator"

if [ "$EUID" -ne 0 ]; then
  echo "Run as root: sudo ./install.sh"
  exit 1
fi

if [ -d "$INSTALL_DIR" ]; then
    echo "Error: Calculator is already installed."
    echo "Please run uninstall.sh first."
    exit 1
fi

echo "=================================="
echo "  Installing Calculatron 3000"
echo "=================================="

echo "[1/8] Creating directories..."
mkdir -p "$INSTALL_DIR"

echo "[2/8] Copying files..."

if [ -d "$REPO_SRC" ]; then
    cp -r "$REPO_SRC/"* "$INSTALL_DIR/"
else
    echo "Error: Source directory $REPO_SRC not found!"
    exit 1
fi

if [ -f "$REPO_REQS" ]; then
    cp "$REPO_REQS" "$INSTALL_DIR/"
fi

echo "[3/8] Installing system dependencies..."
apt update || echo "Update failed, trying to install anyway..."
apt install -y python3 python3-venv python3-tk python3-pip

echo "[4/8] Creating virtual envirnoment..."
python3 -m venv "$INSTALL_DIR/venv"

echo "[5/8] Installing python dependencies..."
"$INSTALL_DIR/venv/bin/pip" install --upgrade pip

if [ -f "$INSTALL_DIR/requirements.txt" ]; then
	"$INSTALL_DIR/venv/bin/pip" install -r "$INSTALL_DIR/requirements.txt"
fi

echo "[6/8] Creating calculator launcher..."
tee /usr/bin/calculator > /dev/null << 'EOF'
#!/usr/bin/env bash
exec /usr/share/calculator/venv/bin/python /usr/share/calculator/gui.py
EOF

chmod +x /usr/bin/calculator

echo "[7/8] Creating profiling launcher..."

tee /usr/bin/stddev > /dev/null << 'EOF'
#!/usr/bin/env bash
exec /usr/share/calculator/venv/bin/python /usr/share/calculator/profiling.py
EOF

chmod +x /usr/bin/stddev

echo "[8/8] Creating menu entry..."
cat << EOF > /usr/share/applications/calculator.desktop
[Desktop Entry]
Version=1.0
Name=Calculatron 3000
Exec=calculator
Icon=accessories-calculator
Terminal=false
Type=Application
Categories=Utility;
EOF

echo "=================================="
echo " Installation complete!"
echo " Run: calculator"
echo " Run: stddev < data.txt"
echo "=================================="
