#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# Configuration
DOWNLOAD_DIR="$HOME/Downloads"
URL="https://downloads.ottomate.io/releases/ottomate-linux-x64-beta.AppImage"
FILE_NAME="ottomate-linux-x64-beta.AppImage"

cat << 'EOF'
       _   _                        _       
      | | | |                      | |      
  ___ | |_| |_ ___  _ __ ___   __ _| |_ ___ 
 / _ \| __| __/ _ \| '_ ` _ \ / _` | __/ _ \
| (_) | |_| || (_) | | | | | | (_| | ||  __/
 \___/ \__|\__\___/|_| |_| |_|\__,_|\__\___|
                                            
                                            
EOF

echo "Welcome to the ottomate setup script. The terminal will ask for your password to install the required dependencies to run it."

# 1. Create Downloads directory if it doesn't exist
mkdir -p "$DOWNLOAD_DIR"

# 2. Download the AppImage
sudo echo "Downloading $FILE_NAME to $DOWNLOAD_DIR..."

if [ -f "$DOWNLOAD_DIR/$FILE_NAME" ]; then
    echo "File already exists at $$DOWNLOAD_DIR/$FILE_NAME. Skipping download."
elif command -v curl >/dev/null 2>&1; then
    curl -L "$URL" -o "$DOWNLOAD_DIR/$FILE_NAME"
elif command -v wget >/dev/null 2>&1; then
    wget -O "$DOWNLOAD_DIR/$FILE_NAME" "$URL"
else
    echo "Error: Neither curl nor wget was found. Please install one and run again." >&2
    exit 1
fi

# 3. Make the AppImage executable
echo "Making AppImage executable..."
chmod +x "$DOWNLOAD_DIR/$FILE_NAME"

# 4. Detect Distro and Install Dependencies
echo "Detecting package manager and installing required dependencies..."

if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS_ID=$ID
    OS_LIKE=$ID_LIKE
else
    OS_ID="unknown"
    OS_LIKE="unknown"
fi

# Match distribution pattern
if [[ "$OS_ID" =~ ^(ubuntu|debian|pop|mint|kali|raspbian)$ ]] || [[ "$OS_LIKE" =~ (debian|ubuntu) ]]; then
    echo "Using APT package manager..."
    sudo apt-get update
    sudo apt-get install -y \
        build-essential \
        pkg-config \
        libssl-dev \
        libasound2-dev \
        libudev-dev \
        libx11-dev \
        libxcb1-dev \
        libxcb-shape0-dev \
        libxcb-xfixes0-dev \
        libxkbcommon-dev \
        libxkbfile-dev \
        libinput-dev \
        libwayland-dev

elif [[ "$OS_ID" =~ ^(fedora|rhel|centos|almalinux|rocky|amzn)$ ]] || [[ "$OS_LIKE" =~ (fedora|rhel) ]]; then
    echo "Using DNF package manager..."
    sudo dnf check-update || true
    sudo dnf install -y \
        gcc gcc-c++ make \
        pkgconf-pkg-config \
        openssl-devel \
        alsa-lib-devel \
        systemd-devel \
        libX11-devel \
        libxcb-devel \
        libxkbcommon-devel \
        libxkbfile-devel \
        libinput-devel \
        wayland-devel

elif [[ "$OS_ID" =~ ^(arch|cachyos|manjaro|endeavouros|garuda)$ ]] || [[ "$OS_LIKE" =~ (arch) ]]; then
    echo "Detected CachyOS / Arch-based system. Using PACMAN..."
    sudo pacman -Sy --needed --noconfirm \
        base-devel \
        pkgconf \
        openssl \
        alsa-lib \
        systemd \
        libx11 \
        libxcb \
        libxkbcommon \
        libxkbfile \
        libinput \
        wayland

elif [[ "$OS_ID" =~ ^(suse|opensuse|opensuse-tumbleweed|opensuse-leap)$ ]] || [[ "$OS_LIKE" =~ (suse|opensuse) ]]; then
    echo "Using ZYPPER package manager..."
    sudo zypper refresh
    sudo zypper install -y \
        gcc gcc-c++ make \
        pkg-config \
        libopenssl-devel \
        alsa-devel \
        libudev-devel \
        libX11-devel \
        libxcb-devel \
        libxkbcommon-devel \
        libxkbfile-devel \
        libinput-devel \
        wayland-devel

else
    # Fallback tool matching if os-release properties are non-standard
    if command -v pacman >/dev/null 2>&1; then
        sudo pacman -Sy --needed --noconfirm base-devel pkgconf openssl alsa-lib systemd libx11 libxcb libxkbcommon libxkbfile libinput wayland
    elif command -v apt-get >/dev/null 2>&1; then
        sudo apt-get update && sudo apt-get install -y build-essential pkg-config libssl-dev libasound2-dev libudev-dev libx11-dev libxcb1-dev libxcb-shape0-dev libxcb-xfixes0-dev libxkbcommon-dev libxkbfile-dev libinput-dev libwayland-dev
    elif command -v dnf >/dev/null 2>&1; then
        sudo dnf install -y gcc gcc-c++ make pkgconf-pkg-config openssl-devel alsa-lib-devel systemd-devel libX11-devel libxcb-devel libxkbcommon-devel libxkbfile-devel libinput-devel wayland-devel
    elif command -v zypper >/dev/null 2>&1; then
        sudo zypper install -y gcc gcc-c++ make pkg-config libopenssl-devel alsa-devel libudev-devel libX11-devel libxcb-devel libxkbcommon-devel libxkbfile-devel libinput-devel wayland-devel
    else
        echo "Error: Package manager not recognized. Please install equivalents manually." >&2
        exit 1
    fi
fi

if [ ! -f /lib/udev/rules.d/ottomate.rules ]; then
    echo 'KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"' | sudo tee -a /lib/udev/rules.d/99-ottomate-input.rules
    sudo udevadm control --reload-rules || true
    sudo udevadm trigger --action=change --sysname-match=uinput || true
fi

echo "--------------------------------------------------------"
echo "Success!"
echo "Distribution dependencies have been updated."
echo "ottomate is starting!"
echo "Launch from the Start Menu or $HOME/Applications/ottomate/$FILE_NAME"
echo "--------------------------------------------------------"

sleep 2

# Launch the AppImage, redirecting stdout, stderr, AND stdin to /dev/null
"$DOWNLOAD_DIR/$FILE_NAME" --no-sandbox >/dev/null 2>&1 &

# Detach the background process from this script's shell
disown

sleep 2

exit