#!/bin/sh

BETA_AVAILABLE=0
THEMES_DIR="/usr/share/ucode/luci/template/themes"

is_rr_inited() {
	[ -f /etc/config/.rr-init ]
}

if [ -d "$THEMES_DIR/routerich" ] && [ ! -e "$THEMES_DIR/routerich-bootstrap" ]; then
	ln -s routerich "$THEMES_DIR/routerich-bootstrap"
fi

STATIC_DIR="/www/luci-static"
if [ -d "$STATIC_DIR/routerich" ] && [ ! -e "$STATIC_DIR/routerich-bootstrap" ]; then
	ln -s routerich "$STATIC_DIR/routerich-bootstrap"
fi

changed=0

set_opt() {
	local key=$1
	local val=$2

	if ! uci -q get "luci.$key" 2>/dev/null; then
		uci set "luci.$key=$val"
		changed=1
	fi
}

set_opt themes.Routerich /luci-static/routerich
set_opt themes.RouterichLite /luci-static/routerich-bootstrap

if uci -q get luci.themes.RouterichBootstrap >/dev/null; then
	uci -q delete luci.themes.RouterichBootstrap
	changed=1
fi

if uci -q get luci.themes.RouterichBeta >/dev/null; then
	uci -q delete luci.themes.RouterichBeta
	changed=1
fi

if [ "$(uci -q get luci.main.mediaurlbase)" = "/luci-static/routerich-beta" ]; then
	uci set luci.main.mediaurlbase=/luci-static/routerich
	changed=1
fi

if uci -q get luci.main.routerich_beta >/dev/null; then
	uci -q delete luci.main.routerich_beta
	changed=1
fi

if [ "$BETA_AVAILABLE" != 1 ] && uci -q get luci.main.routerich_hide_beta >/dev/null; then
	uci -q delete luci.main.routerich_hide_beta
	changed=1
fi

[ ! -L "$THEMES_DIR/routerich-beta" ] || rm -f "$THEMES_DIR/routerich-beta"
[ ! -L "$STATIC_DIR/routerich-beta" ] || rm -f "$STATIC_DIR/routerich-beta"

DEFAULT_THEME="/luci-static/routerich"
if [ "$PKG_UPGRADE" != 1 ] && ! is_rr_inited; then
	uci set luci.main.mediaurlbase="$DEFAULT_THEME"
	changed=1
fi

if [ $changed = 1 ]; then
	uci commit luci
fi

exit 0
