#!/bin/bash
#
# recordum_mv
#
# v0.1 2013-03-20 RE
# v0.2 2018-10-18 RE
# v0.3 2024-02-20 BEH - Allow run as non root
#
# moves an uploaded file from the web directory to a destination
# and change the ownership to any user or recordum (default)
# and also allow privilege change

MYSELF=$( basename $0 )

script_help() {
    cat <<EOF
${MYSELF} help:

This script moves an uploaded file to its destination. It needs root privileges!

Usage: ${MYSELF} <SOURCE> <TARGET> [<USER>] [<PRIVILEGES>]

where:
    SOURCE     ... absolut path / source file
    TARGET     ... absolut path / target file
    USER       ... system user
    PRIVILEGES ... change file privileges use ocatl 0755 or string oug+x

EOF
}

if [[ $# -lt 2 || $# -gt 4 ]]
then
    echo "incorrect number of command line parameters!"
    script_help
    exit 1
fi

SOURCE=$1
TARGET=$2
TGT_USER=${3:-recordum}

if [ ${TGT_USER} != ${USER} -a ${UID} -gt 0 ]
then
    echo "${MYSELF} needs to be run as superuser or ${TGT_USER}. You are ${USER}."
    script_help
    exit 2
fi

/bin/mv ${SOURCE} ${TARGET} || exit 3
/bin/chown ${TGT_USER}:adm ${TARGET} || exit 4

if [[ $# -eq 4 ]]
then
    PRIVILEGES=$4
    /bin/chmod ${PRIVILEGES} ${TARGET} || exit 5
fi

exit 0
