#!/bin/bash

source $(dirname $0)/setman-common.sh
source $(dirname $0)/setman-metadata.sh

show_usage()
{
    echo "Write the requested file from setting item to stdout"
    echo "Usage"
    echo "    setman-restore <settings-item-name> <file-name>"
    echo ""
    echo "Could be called only when setman restore action is running"
    echo "Returns:"
    echo " 0: Data successfully read"
    echo " ${SETMAN_ERROR_INVALID_ARGUMENT}: Illegal argument count"
    echo " ${SETMAN_ERROR_NO_SUCH_FILE_OR_DIRECTORY}: (check log) "
    echo "        Backup path not exists (restore not in progress, or bad backup_dir parameter)"
    echo "        Setting item missing "
    echo "        file not found "
}
if [ "$#" -ne 2 ]; then
    show_usage
    setman-log err "Illegal argument count"
    exit ${SETMAN_ERROR_INVALID_ARGUMENT};
fi

settings_item=$1
file_name=$2
backup_dirs=$(setman-action read-restore-dirs)
if [ $? -ne 0 ]; then
    setman-log err "Backup path not available"
    exit ${SETMAN_ERROR_NO_SUCH_FILE_OR_DIRECTORY};
fi

#The converted backup path is the first in this list, because
#  * when restore is called from webLDC a local backup is created, and it could contain that setting-item,
#       which needs the conversion. In this case we want to find the converted setting-item first, and not the local version of it.
#  * when restore is called during firmware upgrade, the setman-convert-legacy-backup script is called,
#       and it will convert the setting-item only when it's not found in the backups. So in this case the 
#       converted backup will not contain the setting-item.
backup_dirs="${SETMAN_CONVERTED_BACKUP_PATH} ${backup_dirs}"

for backup_dir in ${backup_dirs}; do
    settings_item_dir="${backup_dir}/${SETMAN_SETTINGS_DIR_NAME}/${settings_item}"
    if [ ! -d "${settings_item_dir}" ]; then
        continue
    fi
    file_path=${settings_item_dir}/${file_name}
    if [ ! -f "${file_path}" ]; then
        setman-log err "File not found in setting item ${file_path} (${backup_dir})"
        exit ${SETMAN_ERROR_NO_SUCH_FILE_OR_DIRECTORY};
    fi
    setman-log debug "Restore from file ${file_path}"
    cat ${file_path}
    exit 0
done

setman-log error "Setting item missing: ${settings_item}"
exit ${SETMAN_ERROR_NO_SUCH_FILE_OR_DIRECTORY}
