#!/bin/bash
set -x
# Function to check if a port is in use
port_in_use() {
    lsof -i :$1 >/dev/null
}

# Function to find the next available port
next_available_port() {
    local port=$1
    while port_in_use $port; do
        ((port++))
    done
    echo $port
}

run_tests() {
    local OPTIND
    while getopts 'c:d:t:' OPTION; do
        case "$OPTION" in
            c)
                local conf="$OPTARG"
                ;;
            d)
                local db="$OPTARG"
                ;;
            t)
                local tags=$OPTARG
                ;;
            f)
                local logfile=$OPTARG
                ;;
            *)
                echo "Invalid flag $OPTION."
                exit 1
                ;;
        esac
    done

    if [[ -z $conf ]]; then
        local conf=conf/odoo.conf
    fi
    if [[ -z $db ]]; then
        local db="test"
    fi
    if [[ -z $tags ]]; then
        local tags="--test-enable"
    else
        tags="--test-tags $tags"
    fi
    if [[ -n $logfile ]]; then
        logfile="--logfile $logfile"
    fi

    local port
    port=$(next_available_port 8069)

    clear; psql postgres -c "drop database $db"; odoo/odoo-bin -c "$conf" --http-port \
        $port -d "$db" $tags $logfile --stop-after-init -i ${!#}
}

run_tests "$@"
