set -e  # Abort on error
set -u  # Treat unset variables as an error
set -o pipefail  # Propagate errors in pipelines

# Update package list
echo "Updating package list..."
sudo apt update || { echo "Error: Failed to update package list." >&2; exit 1; }

# Install dependencies
echo "Installing dependencies..."
sudo apt install -y build-essential cmake git || { echo "Error: Failed to install dependencies." >&2; exit 1; }

# Install cmake and make, if not yet installed
echo "Checking for cmake and make..."
which cmake >/dev/null || { echo "cmake not found, installing..."; sudo apt install -y cmake || { echo "Error: Failed to install cmake." >&2; exit 1; }; }
which make >/dev/null || { echo "make not found, installing..."; sudo apt install -y make || { echo "Error: Failed to install make." >&2; exit 1; }; }

# Clone the WolfSSL repository
echo "Cloning WolfSSL repository..."
mkdir -p ../../wolfssl
cd ../../wolfssl
git clone https://github.com/wolfSSL/wolfssl.git || { echo "Error: Failed to clone WolfSSL repository." >&2; exit 1; }

# Change to the wolfssl directory
cd wolfssl

# Create and change to the build directory
echo "Creating build directory..."
mkdir -p build
cd build

# Configure the build
echo "Configuring build with cmake..."
cmake .. || { echo "Error: CMake configuration failed." >&2; exit 1; }

# Compile the source code
echo "Compiling the code..."
make || { echo "Error: Compilation failed." >&2; exit 1; }

# Install the compiled binaries
echo "Installing WolfSSL..."
sudo make install || { echo "Error: Installation failed." >&2; exit 1; }

# Update library cache
echo "Updating library cache..."
sudo ldconfig || { echo "Error: Failed to update library cache." >&2; exit 1; }

echo "WolfSSL installation completed successfully."