#!/bin/bash

# Exit on error
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Parse command line arguments
AUTO_INSTALL=false
for arg in "$@"; do
    case $arg in
        --auto-install)
            AUTO_INSTALL=true
            ;;
    esac
done


# Function to print status messages
print_status() {
    echo -e "${GREEN}[*] $1${NC}"
}

print_error() {
    echo -e "${RED}[!] $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}[!] $1${NC}"
}

# Check if build directory exists, if not create it
if [ ! -d "build" ]; then
    print_status "Creating build directory..."
    mkdir build
fi

# Enter build directory
cd build

# Check if CMake is installed
if ! command -v cmake &> /dev/null; then
    print_error "CMake is not installed. Please install CMake first."
    exit 1
fi

# Check if make is installed
if ! command -v make &> /dev/null; then
    print_error "Make is not installed. Please install Make first."
    exit 1
fi

# Check if pkg-config is installed
if ! command -v pkg-config &> /dev/null; then
    print_error "pkg-config is not installed. Please install pkg-config first."
    print_warning "On Ubuntu/Debian: sudo apt-get install pkg-config"
    print_warning "On Fedora: sudo dnf install pkg-config"
    print_warning "On Arch: sudo pacman -S pkg-config"
    exit 1
fi

# Check if ncurses is installed
if ! pkg-config --exists ncurses; then
    print_error "ncurses is not installed. Please install ncurses first."
    print_warning "On Ubuntu/Debian: sudo apt-get install libncurses-dev"
    print_warning "On Fedora: sudo dnf install ncurses-devel"
    print_warning "On Arch: sudo pacman -S ncurses"
    exit 1
fi

# Configure with CMake
print_status "Configuring with CMake..."
#cmake .. -DCMAKE_BUILD_TYPE=Debug
cmake .. -DCMAKE_BUILD_TYPE=Release

# Build the project
print_status "Building project..."
make -j$(nproc)

# Check if build was successful
if [ $? -eq 0 ]; then
    print_status "Build successful!"
    print_status "Binary location: $(pwd)/dropshell"
else
    print_error "Build failed!"
    exit 1
fi

# Check if user wants to install
if [ $AUTO_INSTALL = true ]; then
    print_status "Auto-installing dropshell..."
    sudo make install
    if [ $? -eq 0 ]; then
        print_status "Installation successful!"
    else
        print_error "Installation failed!"
        exit 1
    fi
else
    read -p "Do you want to install the program? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_status "Installing dropshell..."
        sudo make install
        if [ $? -eq 0 ]; then
            print_status "Installation successful!"
        else
            print_error "Installation failed!"
            exit 1
        fi
    fi
fi

# Return to original directory
cd ..

print_status "Build process completed!" 