#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# (c) 2020 Netdata Incorporated

set -e

webdir="/usr/share/netdata/web"
configdir="/etc/netdata"

usage() {
    cat << EOF
USAGE: switch-netdata-dashboard.sh <dashboard-name>

<dashboard-name> is required, it specifies which dashboard to use. Valid
arguments are 'react' to use the new React dashboard, and 'classic'
to use the old dashboard.

Once run, you can use the new dashboard by performing a valdiating reload
in your browser (Ctrl-Shift-R in most browsers).
EOF
exit 1
}

switch_dashboard() {
    new="${1}"
    path="${webdir}-${new}"

    echo "Switching to ${new} dashboard..."

    for dashboard in classic react ; do
        # shellcheck disable=SC2013
        for item in $(cat ${webdir}-${dashboard}/.files) ; do
            rm -f "${webdir}/${item}"
        done
    done

    cp -a "${path}/." "${webdir}"

    if [ -e "${configdir}/.environment" ] ; then
        if grep -q NETDATA_SELECTED_DASHBOARD "${configdir}/.environment" ; then
            sed -E "s/^NETDATA_SELECTED_DASHBOARD=\".*\"$/NETDATA_SELECTED_DASHBOARD=\"${new}\"/" "${configdir}/.environment"
        else
            echo "NETDATA_SELECTED_DASHBOARD=\"${new}\"" >> "${configdir}/.environment"
        fi
    fi

    exit 0
}

case "${1}" in
    react)
        switch_dashboard react
        ;;
    classic)
        switch_dashboard classic
        ;;
    *)
        usage
        ;;
esac
