#!/bin/bash
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

# Defaults
# --------
Q_BUILD_OVS_FROM_GIT=$(trueorfalse False Q_BUILD_OVS_FROM_GIT)

# Set variables for building OVS from source
OVS_REPO=${OVS_REPO:-https://github.com/openvswitch/ovs.git}
OVS_REPO_NAME=$(basename ${OVS_REPO} | cut -f1 -d'.')
OVS_REPO_NAME=${OVS_REPO_NAME:-ovs}
OVS_BRANCH=${OVS_BRANCH:-branch-3.3}

# Functions

# load_module() - Load module using modprobe module given by argument and dies
#                 on failure
#               - fatal argument is optional and says whether function should
#                 exit if module can't be loaded
function load_module {
    local module=$1
    local fatal=$2

    if [ "$(trueorfalse True fatal)" == "True" ]; then
        sudo modprobe $module || (sudo dmesg && die $LINENO "FAILED TO LOAD $module")
    else
        sudo modprobe $module || (echo "FAILED TO LOAD $module" && sudo dmesg)
    fi
}

# prepare_for_compilation() - Fetch ovs git repository and install packages needed for
#                             compilation.
function prepare_for_ovs_compilation {
    OVS_DIR=$DEST/$OVS_REPO_NAME

    if [ ! -d $OVS_DIR ] ; then
        # We can't use git_clone here because we want to ignore ERROR_ON_CLONE
        git_timed clone $OVS_REPO $OVS_DIR
        cd $OVS_DIR
        git checkout $OVS_BRANCH
    else
        # Even though the directory already exists, call git_clone to update it
        # if needed based on the RECLONE option
        git_clone $OVS_REPO $OVS_DIR $OVS_BRANCH
        cd $OVS_DIR
    fi

    # TODO: Can you create package list files like you can inside devstack?
    install_package autoconf automake libtool gcc patch make
}

# load_ovs_kernel_modules() - load openvswitch kernel module
function load_ovs_kernel_modules {
    load_module openvswitch
    load_module vport-geneve False
    sudo dmesg | tail
}

# reload_ovs_kernel_modules() - reload openvswitch kernel module
function reload_ovs_kernel_modules {
    set +e
    ovs_system=$(sudo ovs-dpctl dump-dps | grep ovs-system)
    if [ -n "$ovs_system" ]; then
        sudo ovs-dpctl del-dp ovs-system
    fi
    set -e
    sudo modprobe -r vport_geneve
    sudo modprobe -r openvswitch
    load_ovs_kernel_modules
}

# compile_ovs() - Compile OVS from source and load needed modules.
#                 Accepts two optional parameters:
#                   - first optional parameter defines prefix for ovs compilation
#                   - second optional parameter defines localstatedir for ovs single machine runtime
#                 Env variables OVS_REPO_NAME, OVS_REPO and OVS_BRANCH must be set
function compile_ovs {
    local _pwd=$PWD
    local prefix=$1
    local localstatedir=$2

    if [ -n "$prefix" ]; then
        prefix="--prefix=$prefix"
    fi

    if [ -n "$localstatedir" ]; then
        localstatedir="--localstatedir=$localstatedir"
    fi

    prepare_for_ovs_compilation

    if [ ! -f configure ] ; then
        ./boot.sh
    fi
    if [ ! -f config.status ] || [ configure -nt config.status ] ; then
        ./configure $prefix $localstatedir
    fi
    make -j$(($(nproc) + 1))
    sudo make install
    reload_ovs_kernel_modules

    cd $_pwd
}

# action_service - call an action over openvswitch service
#                  Accepts one parameter that can be either
#                  'start', 'restart' and 'stop'.
function action_openvswitch {
    local action=$1

    if is_ubuntu; then
        ${action}_service openvswitch-switch
    elif is_fedora; then
        ${action}_service openvswitch
    fi
}

# start_new_ovs() - removes old ovs database, creates a new one and starts ovs
function start_new_ovs {
    # DB path must match the compiled --prefix=/usr/local sysconfdir
    sudo rm -f /usr/local/etc/openvswitch/conf.db /usr/local/etc/openvswitch/.conf.db~lock~
    sudo /usr/local/share/openvswitch/scripts/ovs-ctl start
}

# stop_new_ovs() - stops ovs
function stop_new_ovs {
    local ovs_ctl='/usr/local/share/openvswitch/scripts/ovs-ctl'

    if [ -x $ovs_ctl ] ; then
        sudo $ovs_ctl stop
    fi
}

# remove_ovs_packages() - removes old ovs packages from the system
function remove_ovs_packages {
    for package in openvswitch openvswitch-switch openvswitch-common; do
        if is_package_installed $package; then
            uninstall_package $package
        fi
    done
}


# load_conntrack_gre_module() - loads nf_conntrack_proto_gre kernel module
function load_conntrack_gre_module {
    load_module nf_conntrack_proto_gre False
}
