#!/bin/sh

MY_SERVICE_NAME=configsync
CONFIGSYNC_CONFIGURATION_FILE=/tmp/p1905.cfg

PATH_TO_CONFIGSYNC_EXECUTOR=/usr/share/configsync.d
CS_CONFIGURATION_PATH=/tmp/configsync
CS_CHANGE_PATH=/tmp/.uci_configsync
CS_MD5SUMS=/tmp/cs_md5sums
CS_MD5SUMS2=/tmp/cs_md5sums2
CS_SERVICES_TO_SYNC="wifi_schedule wireless system parental_control ghn station_quota"
CS_SERVICELIST=/tmp/cs_servicelist

CS_TEMP_CONFIG_PATH=/tmp/tmpconfig
CS_TEMP_CHANGE_PATH=/tmp/.tmpuci_config
CS_IMPORTSERVICELIST=/tmp/cs_importservicelist
CS_PREFIX=cstmp

CSEmptyString="<To be deleted!>"

my_logger() {
   logger -t configsync "${@}"
}

uci_cs() {
    if [ "$1" = "set" ] && [ "${2#*=}" = "" ]; then
        uci -q -p ${CS_CHANGE_PATH} -c ${CS_CONFIGURATION_PATH} set "${2}${CSEmptyString}"
    else
        uci -q -p ${CS_CHANGE_PATH} -c ${CS_CONFIGURATION_PATH} "${@}"
    fi
}

delete_sections_cs() {
    while uci -q -p ${CS_CHANGE_PATH} -c ${CS_CONFIGURATION_PATH} delete ${1}.@${2}[-1] > /dev/null 2>&1; do :; done
}

delete_sections() {
    while uci_remove ${1} @${2}[-1] > /dev/null 2>&1; do :; done
}

uci_tmp() {
    if [ "$1" = "set" ] && [ "${2#*=}" = "${CSEmptyString}" ]; then
        uci -q -P ${CS_TEMP_CHANGE_PATH} -c ${CS_TEMP_CONFIG_PATH} set "${2%=*}="
    else
        uci -q -P ${CS_TEMP_CHANGE_PATH} -c ${CS_TEMP_CONFIG_PATH} "${@}"
    fi
}

delete_sections_tmp() {
    while uci -q -P ${CS_TEMP_CHANGE_PATH} -c ${CS_TEMP_CONFIG_PATH} delete ${1}.@${2}[-1] > /dev/null 2>&1; do :; done
}

update_md5sum() {
    my_logger "update_md5sum: Service ${1}"
    local tmpfile=$(mktemp)
    grep -vE "/${1}\$" $CS_MD5SUMS > $tmpfile
    md5sum /etc/config/${1} >> $tmpfile
    mv -f $tmpfile $CS_MD5SUMS
}

check_md5sum() {
    if [ "$(md5sum /etc/config/${1} 2>&1)" = "$(grep -E "/${1}\$" $CS_MD5SUMS)" ]; then
        my_logger "check_md5sum: Service ${1} checksum identical"
        return 0
    else
        my_logger "check_md5sum: Service ${1} checksum different"
        return 1
    fi
}

add_to_list() {
    if ! grep -E "^${2}\$" $1 >/dev/null 2>&1; then echo ${2} >> $1;fi
}

wait_stable_config() {
    return 0
}

