#!/usr/bin/env bash
### Copyright 1999-2026. WebPros International GmbH. All rights reserved.

#
# Helper utility for file operations with proftpd's configuration files.
#

usage() {
    cat << EOH

Usage: $0 [options]

 Helper utility for working with proftpd's configuration files

OPTIONS:
 -w file - Write content from stdin to the specified file. Makes backup
           of target file.

EOH
}

write() {

    filename="$1"

    # Check target file can be replaced
    if [ -f "$filename" ] ; then
        if [ ! -w "$filename" -o ! -r "$filename" ] ; then
            echo "Can not read/write to $filename" >&2
            return 100
        fi
    fi

    # Put new content into temporary file
    tmpfile=`mktemp "$filename".XXXXXX`
    if [ "x$?" != "x0" -o ! -w "$tmpfile" ] ; then
        echo "Can not create temporary file $tmpfile" >&2
        return 101
    fi

    cat > "$tmpfile"
    if [ "x$?" != "x0" ] ; then
        echo "Error writing to $tmpfile" >&2
        rm -f "$tmpfile"
        return 101
    fi

    # Remove existing target file
    if [ -f "$filename" ] ; then
        rm -f "$filename"
        if [ "x$?" != "x0" ] ; then
            echo "Can not remove existing file $filename" >&2
            rm -f "$tmpfile"
            return 100
        fi
    fi

    # Commit changes to target file (disable interactivity in mv)
    mv -f "$tmpfile" "$filename"
    if [ "x$?" != "x0" ] ; then
        ERROR=$?
        rm -f "$tmpfile"
        return $ERROR
    fi

    # Correct owner & permissions
    chmod 644 "$filename"
    chown "root":"root" "$filename"

    return $?
}

if [ $# -eq 0 ] ; then
    usage
    exit 0
fi

getopts "w:" OPTION

ERROR=0
case $OPTION in
    w)
        write "$OPTARG"
        ERROR=$?
        ;;
    *)
        usage
        ERROR=1
        ;;
esac

exit $ERROR
