#!/bin/bash

POSITIONAL_ARGS=()
KEEPDB='false'

while [[ $# -gt 0 ]]; do
  case $1 in
    -m|--mode)
      MODE="$2"
      shift # past argument
      shift # past value
      ;;
    -t|--topology)
      TOPOLOGY="$2"
      shift # past argument
      shift # past value
      ;;
    -s|--sdnconfig)
      SDNCONFIG="$2"
      shift # past argument
      shift # past value
      ;;
    --keepdb)
      KEEPDB="true"
      shift # past argument
      ;;
    -*|--*)
      echo "Unknown option $1"
      exit 1
      ;;
    *)
      POSITIONAL_ARGS+=("$1") # save positional arg
      shift # past argument
      ;;
  esac
done

start_gosdn () {
    # Start controller
    cd controller
    GOSDN_ADMIN_PASSWORD="admin" make start &
    pid=$!
    cd ..
}

if [ $MODE = 'start' ];
then
    echo "Need sudo rights."
    sudo echo "sudo rights granted"
    # Start databases, etc.
    docker compose up -d

    # Start clab topology
    if [ $KEEPDB = 'true' ];
    then
        sudo containerlab deploy -t $TOPOLOGY
        start_gosdn
    else
        sleep 5
        start_gosdn
        ./artifacts/venv-manager --mode deploy --topology $TOPOLOGY  --sdnconfig $SDNCONFIG
    fi

    echo "#########################################################################################"
    echo "Initialisation finished. You will now see the output of goSDN. Press Ctrl+C to stop it."
    wait $pid
fi

if [ $MODE = 'stop' ];
then
    docker compose down
    sudo containerlab destroy -t $TOPOLOGY -c
    rm -f dev_env_data/clab/.*.bak
fi
