#!/bin/sh
ICPGW_BACKEND_DIR="/barix/apps/icpgw"
DEFAULT_DIR="/mnt/data/prerecorded_messages/default"
RAW_FILES_DIR="/mnt/data/prerecorded_messages/"
BACKUP_FILES_LOCATION="/mnt/data/config/icpgw_config/"

### Check for DEFAULT_DIR, if not found create it using the mkdir ##
[ ! -d "$DEFAULT_DIR" ] && mkdir -p "$DEFAULT_DIR"

### Copy the default audio button message to its correct directory on the SD card
cp $ICPGW_BACKEND_DIR/default.mp3 $DEFAULT_DIR/default.mp3
### Make a second copy which the app will be working with
cp $ICPGW_BACKEND_DIR/default.mp3 $RAW_FILES_DIR/default.mp3


# [ ! -d "$BACKUP_FILES_LOCATION" ] && mkdir -p "$BACKUP_FILES_LOCATION"

if [ -d "$BACKUP_FILES_LOCATION" ] ; then
  ### Restore the user configurations only if the directory exists
  echo "Restoring user configurations..."
  cp $BACKUP_FILES_LOCATION/*backup.json $ICPGW_BACKEND_DIR/
  echo "Done!"
else
  ### Otherwise just create the backup directory
  ### This can only happen in the case when the FW is uploaded to a new device
  mkdir -p "$BACKUP_FILES_LOCATION"
  echo "Backup directory created"
fi


#patch 

# icpgw
if [ -z "$(uci -q get icpgw.rtp)" ]; then
    uci set icpgw.rtp=section
    uci set icpgw.rtp.enabled='False'
    uci set icpgw.rtp.ip='0.0.0.0'
    uci set icpgw.rtp.port='1234'
    uci set icpgw.rtp.format='PCM16BE'
    uci commit  
fi

if [ -z "$(uci -q get icpgw.modbus)" ]; then
    uci set icpgw.modbus=section
    uci set icpgw.modbus.enabled='False'
    uci set icpgw.modbus.port='502'
    uci commit
fi

if [ -z "$(uci -q get icpgw.pregong)" ]; then
    uci set icpgw.pregong=section
    uci set icpgw.pregong.enabled='False'
    uci commit
fi

if [ -z "$(uci -q get icpgw.relay)" ]; then
    uci set icpgw.relay=section
    uci set icpgw.relay.enabled='False'
    uci commit
fi
