#!/bin/bash
#
# recordum_cp
#
# v0.1 2013-03-22 RE
# v0.2 2013-07-15 RE
# v0.3 2018-10-18 RE
#
# copies a file and optionally changes the ownership too
# and also allow privilege change

MYSELF=$( basename $0 )

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

This script copies and optional changes the ownership (requires root).

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

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

EOF
}

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

SOURCE="$1"
TARGET="$2"
TGT_USER="$3"
TGT_GROUP="$4"
TGT_PRIVS="$5"

# create target file with zero size
# >${TARGET}  ## WHY!?  I commented this because is MAKES NO SENSE (beh) but leave it here just in case I am missing something.

# copy
/bin/cp ${SOURCE} ${TARGET} || exit 3
# Change User
if [ -n "${TGT_USER}" -a "${TGT_USER}" != "$( id -un )" ]; then
    if [ "$(id -u)" -ne 0 ]; then
        echo "Cant change effective user unless run as root!"
        exit 3
    fi
    /bin/chown ${TGT_USER} ${TARGET} || exit 4
fi
# Change Group
if [ -n "${TGT_GROUP}" ]; then
    /bin/chgrp ${TGT_GROUP} ${TARGET} || exit 5
fi
# Change Perms
if [ -n "${TGT_PRIVS}" ]; then
    /bin/chmod ${TGT_PRIVS} ${TARGET} || exit 7
fi

exit 0
