#!/bin/sh

# Short-Description: Open vSwitch VTEP emulator
# Description:       Initializes the Open vSwitch VTEP emulator

export OVS_LOGDIR=/var/log/openvswitch-vtep
export OVS_RUNDIR=/run/openvswitch-vtep
export OVS_PKGDATADIR=/usr/share/openvswitch
export OVS_DBDIR=/etc/openvswitch-vtep
etcdir=/etc/openvswitch-vtep

. /usr/share/openvswitch/scripts/ovs-lib

start () {
    ovs-dpctl dump-dps 2>&1 | grep ovs-system > /dev/null
    rc=$?
    if [ $rc -eq 0 ]; then
        cat << EOF >&2
An already running copy of ovs-vswitchd detected in current namespace.

Running multiple instances of ovs-vswitchd in the same namespace is not
supported.
EOF
        exit 1
    fi

    if [ ! -e "$etcdir/conf.db" ]; then
        ovsdb-tool create $etcdir/conf.db $OVS_PKGDATADIR/vswitch.ovsschema
    fi

    if [ ! -e "$etcdir/vtep.db" ]; then
        ovsdb-tool create $etcdir/vtep.db $OVS_PKGDATADIR/vtep.ovsschema
    fi

    if [ ! -e "$etcdir/ovsclient-cert.pem" ]; then
        export RANDFILE="/root/.rnd"
        cd $etcdir && ovs-pki req ovsclient && ovs-pki self-sign ovsclient
    fi

    if [ ! -d $OVS_RUNDIR ]; then
        install -d -m 755 -o root -g root $OVS_RUNDIR
    fi

    ovsdb-server --pidfile --detach --log-file --remote \
        punix:$OVS_RUNDIR/db.sock \
        --remote=db:hardware_vtep,Global,managers \
        --private-key=$etcdir/ovsclient-privkey.pem \
        --certificate=$etcdir/ovsclient-cert.pem \
        --bootstrap-ca-cert=$etcdir/vswitchd.cacert \
        $etcdir/conf.db $etcdir/vtep.db

    modprobe openvswitch

    ovs-vswitchd --pidfile --detach --log-file \
        unix:$OVS_RUNDIR/db.sock
}

stop () {
    stop_daemon ovs-vswitchd
    stop_daemon ovsdb-server
}

case $1 in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|force-reload)
        stop
        start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0
