#!/bin/bash

set -e

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check for Curl
if ! command_exists curl; then
    echo "Error: curl is not installed. Please install curl and try again."
    exit 1
fi

################
# Install Docker
################

echo "Checking Docker ..."
curl -fsSL https://www.datasquirel.com/packages/docker.sh | bash

###########################
# Install Required Packages
###########################

echo "Checking Utils ..."
curl -fsSL https://www.datasquirel.com/packages/utils.sh | bash

######################
# Verify Installations
######################

# Check for Wget
if ! command_exists wget; then
    echo "Error: wget is not installed. Please install wget and try again."
    exit 1
fi

# Check for Docker
if ! command_exists docker; then
    echo "Error: Docker is not installed. Please install Docker and try again."
    exit 1
fi

# Check for Docker Compose
if docker compose version >/dev/null 2>&1; then
    echo "Docker Compose plugin ('docker compose') is installed."
    DOCKER_COMPOSE_COMMAND="docker compose"
elif command_exists docker-compose; then
    echo "Standalone Docker Compose ('docker-compose') is installed."
    DOCKER_COMPOSE_COMMAND="docker-compose"
else
    echo "Error: Neither 'docker compose' nor 'docker-compose' is installed. Please install Docker Compose and try again."
    exit 1
fi

echo "Docker and Docker Compose are installed."

# Check for Zip and Unzip
if ! command_exists zip; then
    echo "Error: zip is not installed. Please install zip and unzip and try again."
    exit 1
fi

if ! command_exists unzip; then
    echo "Error: unzip is not installed. Please install unzip and try again."
    exit 1
fi

#############
# Install Bun
#############

BUN=$HOME/.bun/bin/bun

if [[ ! -f "$BUN" ]]; then
    echo "Bun not installed. Installing ..."
    curl -fsSL https://bun.sh/install | bash -s "bun-v1.2.0"
    source ~/.bashrc
fi

######################
# Install Bun Packages
######################

echo "Installing packages ..."
$BUN add -g inquirer js-yaml lodash

#######################
# Fire up the Installer
#######################

ROOT_DIR=$HOME/.dsql
INSTANCES_DIR=$ROOT_DIR/instances
SETUP_DIR=$ROOT_DIR/setup
INSTALL_TS_FILE=$SETUP_DIR/dsql-install.ts

mkdir -p $SETUP_DIR
mkdir -p $INSTANCES_DIR

INSTALL_TS_URL="https://www.datasquirel.com/api/media/install-ts"

wget -O $INSTALL_TS_FILE $INSTALL_TS_URL

cd $HOME

$BUN $INSTALL_TS_FILE </dev/tty
