#!/usr/bin/env bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_DIR="$HOME/.local/opt/BEANalyzer_UltraPro"
DESKTOP_DIR="$HOME/.local/share/applications"
BIN_DIR="$HOME/.local/bin"
LAUNCHER="$BIN_DIR/beanalyzer-ultrapro"
DESKTOP_FILE="$DESKTOP_DIR/beanalyzer-ultrapro.desktop"

mkdir -p "$APP_DIR" "$DESKTOP_DIR" "$BIN_DIR"

echo "Installing BEANalyzer UltraPro to:"
echo "$APP_DIR"

rm -rf "$APP_DIR/BEANalyzer_UltraPro"
cp -R "$SCRIPT_DIR/BEANalyzer_UltraPro" "$APP_DIR/"

cat > "$LAUNCHER" <<EOF
#!/usr/bin/env bash
set -e
APP_DIR="\$HOME/.local/opt/BEANalyzer_UltraPro/BEANalyzer_UltraPro"
VENV_DIR="\$APP_DIR/.venv"

cd "\$APP_DIR"

PYTHON_BIN=""
for candidate in python3.12 python3; do
    if command -v "\$candidate" >/dev/null 2>&1; then
        PYTHON_BIN="\$(command -v "\$candidate")"
        break
    fi
done

if [ -z "\$PYTHON_BIN" ]; then
    zenity --error --text="Python 3.12 was not found. Install python3.12 and python3.12-venv." 2>/dev/null || echo "Python 3.12 was not found."
    exit 1
fi

if [ ! -x "\$VENV_DIR/bin/python" ]; then
    "\$PYTHON_BIN" -m venv "\$VENV_DIR"
fi

source "\$VENV_DIR/bin/activate"
python -m pip install --upgrade pip setuptools wheel >/tmp/beanalyzer_pip.log 2>&1
python -m pip install -r requirements.txt >>/tmp/beanalyzer_pip.log 2>&1
python beanalyzer_ultrapro.py
EOF

chmod +x "$LAUNCHER"

cat > "$DESKTOP_FILE" <<EOF
[Desktop Entry]
Type=Application
Name=BEANalyzer UltraPro
Comment=Toyota/Lexus BEAN MPX Laboratory
Exec=$LAUNCHER
Icon=$APP_DIR/BEANalyzer_UltraPro/assets/app_icon.png
Terminal=false
Categories=Development;Engineering;Utility;
StartupNotify=true
EOF

chmod +x "$DESKTOP_FILE"
update-desktop-database "$DESKTOP_DIR" >/dev/null 2>&1 || true

echo
echo "Installed."
echo "You can now open BEANalyzer UltraPro from your application launcher."
echo
echo "If serial ports fail, add your user to dialout:"
echo "sudo usermod -a -G dialout \$USER"
echo "Then log out and log back in."
