#!/bin/bash

# Define variables
URL="https://install.speedtest.net/app/cli/ookla-speedtest-1.2.0-linux-x86_64.tgz"
TAR_FILE="ookla-speedtest-1.2.0-linux-x86_64.tgz"
TMP_DIR="/tmp/speedtest"
BIN_DIR="/usr/local/bin"
MAN_DIR="/usr/local/share/man/man5"
DOC_DIR="/usr/local/share/doc/speedtest"

# Ensure the script is run as root
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root or with sudo."
   exit 1
fi

# Create necessary directories only if they do not exist
[[ ! -d "$TMP_DIR" ]] && mkdir "$TMP_DIR"
[[ ! -d "$MAN_DIR" ]] && mkdir -p "$MAN_DIR"
[[ ! -d "$DOC_DIR" ]] && mkdir -p "$DOC_DIR"

# Change to temporary directory
cd "$TMP_DIR" || exit

# Download the file
echo "Downloading Speedtest CLI..."
wget -q --show-progress "$URL" -O "$TAR_FILE"

# Extract the tar file
echo "Extracting files..."
tar -xzf "$TAR_FILE"

# Move the binary to /usr/local/bin
echo "Installing Speedtest CLI binary..."
mv -f speedtest "$BIN_DIR/"

# Set execute permissions for binary
chmod +x "$BIN_DIR/speedtest"

# Move the man page to /usr/local/share/man/man5/
echo "Installing man page..."
mv -f speedtest.5 "$MAN_DIR/"

# Move the markdown documentation to /usr/local/share/doc/speedtest/
echo "Installing documentation..."
mv -f speedtest.md "$DOC_DIR/"

# Clean up temporary files
echo "Cleaning up..."
rm -rf "$TMP_DIR"

# Update man database
mandb

# Verify installation
if command -v speedtest &> /dev/null; then
    echo "Speedtest CLI installed successfully!"
else
    echo "Installation failed."
    exit 1
fi
