#!/bin/bash


if [[ $(cat /etc/*-release | grep "Ubuntu") ]]; then

    if [ -z "$(command -v curl)" ] || [ -z "$(command -v sqlite3)" ] || [ -z "$(command -v jq)" ]; then
        apt update -y;
        apt upgrade -y;
        apt install epel-release -y;
        apt install sqlite3 htop nano wget curl nload jq -y;
    fi
    
    cd /etc
    wget https://cdn.udinweb.com/limit-ip/iplimit.tar.gz
    tar -xzvf iplimit.tar.gz
	rm -rf iplimit.tar.gz
    cd iplimit
    
	script_path="/etc/iplimit/"
	script_file="/etc/iplimit/run.sh"
    service_name="iplimit"
    chmod +x "$script_file"
    
	
    DATABASE_FILE="limit.db"

    # Create the SQLite database file
	sqlite3 "$DATABASE_FILE" <<EOF
CREATE TABLE IF NOT EXISTS ports (
    'port' INTEGER NOT NULL DEFAULT '0',
    'limit' INTEGER NOT NULL DEFAULT 2,
    'speed' TEXT NOT NULL DEFAULT '0',
    'ignore' INTEGER DEFAULT 0
);
EOF

	echo "SQLite database file '$DATABASE_FILE' created with ports table."
    
# Create the systemd service unit file
cat <<EOL > "/etc/systemd/system/$service_name.service"
[Unit]
Description=IP Limit Bash Script Service
After=network.target
Wants=network.target

[Service]
Type=simple
WorkingDirectory=$script_path
ExecStart=$script_file

[Install]
WantedBy=multi-user.target
EOL
    echo "Service '$service_name' created!"
    # Reload systemd and start the service
    systemctl daemon-reload
    systemctl start "$service_name"
    
    # Enable the service to start on boot
    systemctl enable "$service_name"
    
    # Check the status of the service
    systemctl status "$service_name"
	
	if [ "$EUID" -ne 0 ]; then
	  echo "Please run this script with sudo or as root."
	  exit 1
	fi

	# Content of the iplimit script
	IPLIMIT_SCRIPT_CONTENT="#!/bin/bash\ncd /etc/iplimit\n bash iplimit.sh \"\$@\""

	# Create /bin/iplimit and add the content
	echo -e "$IPLIMIT_SCRIPT_CONTENT" > /bin/iplimit

	# Make the script executable
	chmod +x /bin/iplimit
	echo "Iplimit install and configured completely"
else
    echo "This should only be run on ubuntu\n";
    exit 1;
fi