#!/bin/bash

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

show_usage()
{
    echo "Archive data from stdin to given settings item with given filename"
    echo "Usage"
    echo "    setman-backup <settings-item-name> <file-name>"
    echo ""
    echo "Could be called only when setman backup action is running"
    echo "Returns:"
    echo " 0: Data successfully saved"
    echo " ${SETMAN_ERROR_INVALID_ARGUMENT}: Illegal argument count"
    echo " ${SETMAN_ERROR_NO_SUCH_FILE_OR_DIRECTORY}: Backup path not exists (backup not in progress, or bad backup_dir parameter)"
    echo " ${SETMAN_ERROR_FILE_ALREADY_EXISTS}: File already exists (same file writed more times to same setting-item)"
}
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_dir=$(setman-action read-backup-dir)
if [ $? -ne 0 ]; then
    setman-log err "Backup path not available"
    exit ${SETMAN_ERROR_NO_SUCH_FILE_OR_DIRECTORY};
fi
backup_dir="${backup_dir}/${SETMAN_SETTINGS_DIR_NAME}"
if [ ! -d "${backup_dir}" ];
then
    setman-log err "Backup path not exists"
    exit ${SETMAN_ERROR_NO_SUCH_FILE_OR_DIRECTORY};
fi

file_path="${backup_dir}/${settings_item}/${file_name}"
if [ -f "${file_path}" ]; then
    setman-log err "File already exists: ${file_path}"
    exit ${SETMAN_ERROR_FILE_ALREADY_EXISTS};
fi
directory_name=$(dirname "${file_path}")
[ -d "${directory_name}" ] || mkdir -p "${directory_name}"
setman-log debug "Backup to file ${file_path}"
cat - > "${file_path}"
