#!/bin/bash
DATABASE_FILE="limit.db"

# Function to execute arbitrary SQL query
execute_query() {
    local query="$1"
    sqlite3 -csv "$DATABASE_FILE" "$query"
	#echo "$DATABASE_FILE" "$query"
}

# Function to insert data into a table
insert_port() {
	local port="$1"
    execute_query "INSERT INTO 'ports' (port) VALUES ('$port');"
}

# Function to insert data into a table
insert_ports() {
	local cols="$1"
    local vals="$2"
    execute_query "INSERT INTO 'ports' ($cols) VALUES $vals;"
}

add_port() {
	local port="$1"
	exist=$(get_port $port)
	echo $exist
	if [ -z "$exist" ]; then
		insert_port $port
	fi
	get_port $port
}

# Function to update records in a table
update_port() {
    local port="$1"
	local col="$2"
    local val="$3"
	if [ -z "$val" ]; then
		execute_query "UPDATE ports set $col WHERE port='$port';"
	else
		execute_query "UPDATE ports set '$col'='$val' WHERE port='$port';"
	fi
	#view_ports $port
}

# Function to delete records from a table
delete_port() {
    local port="$1"
    execute_query "DELETE FROM 'ports' WHERE port='$port';"
}

get_port() {
	local port="$1"
	#echo "SELECT * FROM 'ports' WHERE port='$port'"
    execute_query "SELECT * FROM 'ports' WHERE port='$port'"
}

get_ports() {
    execute_query "SELECT * FROM 'ports'"
}

search_ports() {
	local col="$1"
	local val="$2"
	if [ -z "$val" ]; then
		execute_query "SELECT * FROM 'ports' WHERE $col"
	else
		execute_query "SELECT * FROM 'ports' WHERE '$col'='$val'"
	fi
}

view_ports() {
	port="$1"
	if [ -n "$port" ]; then
		sqlite3 -column -header limit.db "SELECT * FROM ports WHERE port='$port';"
	else
		sqlite3 -column -header limit.db "SELECT * FROM ports;"
	fi
} 

#add_port $1
#delete_port $1
#get_port 25698
#update_port $1 $2 $3
#res=$(get_ports)
#echo ${res[@]}

# Example usage
#create_table "users" "id INTEGER PRIMARY KEY, name TEXT, age INTEGER"
#insert_port "port" "20489"
#insert_ports "port" "(20482),(20598),(20796)"
#search_ports "users" "age > 25"
#update_port "26789" "limit = 5,speed = '1mbps'"
#update_port "26789" "limit" "5"
#delete_port "26987"
#get_ports
#search_ports "limit>2,speed = 1mbps"
#search_ports "limit" "2"
