#!/bin/bash
#
# ** header v3.0
# This file is a part of the CaosDB Project.
#
# Copyright (C) 2018 Research Group Biomedical Physics,
# Max-Planck-Institute for Dynamics and Self-Organization Göttingen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ** end header
#

LOC_DROPOFFBOX=$(awk < ./conf/ext/server.conf '{ if ($1 == "DROP_OFF_BOX") print $3 }')
DB_USER=__DB_USER__
DB_GROUP=__DB_GROUP__
CMD_CHOWN=__CMD_CHOWN__

if [[ "$1" = "--test" ]]; then
    exit 0
fi

# Tests whether file/folder is in the DropOffBox. 
# This does not actually test whether the file/folder exists!
# @return: true/false
function file_is_in_DropOffBox {
    # $1 : absolute filename
    if [ "${1##$LOC_DROPOFFBOX}" != "${1}" ]; then
        true
    else
        false
    fi
}

# Echoes the absolute filename (in case a relative path is given).
# @return: absolute filename
function get_abs_filename {
    # $1 : relative filename
    if [ -d "$(dirname "$1")" ]; then
        echo "$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
    fi
}

# one argument expected.
if [[ $# -ne 1 ]]; then
	# wrong number of arguments -> exit with error.
	>&2 echo "One argument expected."
	exit 1
fi

# file exists?
if [ ! -e $1 ]; then
	# file does not exist -> exit with error.
	>&2 echo "File $1 does not exist."
	exit 2
fi

# convert to absolute path
FILE_PATH=$(get_abs_filename $1)

# file in DropOffBox?
if ! file_is_in_DropOffBox $FILE_PATH ; then
    # file not in DropOffBox -> exit with error 
	>&2 echo "File is not in DropOffBox."
    exit 3
fi

# make $DB_USER the file-owner and 
$CMD_CHOWN -R $DB_USER:$DB_GROUP $FILE_PATH



