#!/bin/sh

DESC="Configuration files"

LOADED_CONFIG_VERSION="/data/version_config"
# Content can be 1 (partition1) or 2 (partition2)

CONFIG_PATH="/data/config"

p1=`cat /proc/cmdline | grep ubi.mtd=3 | wc -l`
p2=`cat /proc/cmdline | grep ubi.mtd=4 | wc -l`


start() {
    echo "start"
    if [ -f $LOADED_CONFIG_VERSION ];
    then
        # File exist
        CONFIG_VERSION=`cat "$LOADED_CONFIG_VERSION"`
        if [ "$CONFIG_VERSION" == "1" ] && [ $p2 -gt 0 ] && [ $p1 = 0 ];
        then
            echo "Running P2 and config loaded of of P1. Reload config..."
            install 2
        elif [ "$CONFIG_VERSION" == "2" ] && [ $p1 -gt 0 ] && [ $p2 = 0 ];
        then
            echo "Running P1 and config loaded of of P2. Reload config..."
            install 1
        fi

    else
        # File does not exist
        if [ $p2 -gt 0 ] && [ $p1 = 0 ];
        then
            echo "Running P2. Reload config..."
            install 2
        elif [ $p1 -gt 0 ] && [ $p2 = 0 ];
        then
            echo "Running P1. Reload config..."
            install 1
        fi
    fi
    echo "done"
}
stop() {
    echo "stopped"
}
restart() {
    start
}
install(){
    echo "Install... Loading configurations for P$1"
    RECOVER_FOLDER="$CONFIG_PATH/$1/"
    if [ -d $RECOVER_FOLDER ];
    then
        # file exist
        cp -f $RECOVER_FOLDER/*.json $CONFIG_PATH
        echo $1 > $LOADED_CONFIG_VERSION

    else
        echo "RECOVER_FOLDER $RECOVER_FOLDER does not exist..."
    fi

}

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

exit $?
