#!/bin/bash
# set -x

app_path_default='/opt/plugandwork/apps/rce/current'


main() {
    parse_opts "$@"

    # Overwrite config files (as per Olivier request in https://www.wrike.com/open.htm?id=435601922 )
    find /opt/plugandwork/config/ -maxdepth 1 -type f -exec cp {} ${opt_app_path}/config/ \;

    # Overwrite service files (as per Olivier request in https://www.wrike.com/open.htm?id=1080097165 )
    find /opt/plugandwork/config/services/ -maxdepth 1 -type f \( -name \*.service -o -name \*.target \) -exec cp {} ${opt_app_path}/services/ \;

    test `id -u --name` != 'webapp' && chown -R webapp:webapp ${opt_app_path}/config ${opt_app_path}/services

    return 0  # avoid bad exit code because of `test` just above
}


die() {
    printf '%s\n' "$1" >&2
    exit 1
}


die_show_help() {
    show_help
    exit 2
}


show_help() {
    >&2 echo "Usage: $0 [-h|--help] [--app_path]"
}


parse_opts() {
    # AF: Put the short version of argument after |
    # http://perldoc.perl.org/Getopt/Long.html
    parsed_opts=$(
    perl -MGetopt::Long -le '
        @options = (
        "app_path=s",
        "help|h!",
        );
        Getopt::Long::Configure "bundling";
        $q="'\''";
        GetOptions(@options) or exit 1;
        for (map /(\w+)/, @options) {
        eval "\$o=\$opt_$_";
        $o =~ s/$q/$q\\$q$q/g;
        print "opt_$_=$q$o$q"
        }' -- "$@"
    ) || die_show_help

    eval "$parsed_opts"
    # and then use $opt_foo, $opt_bar...
    # note: it will clean previously set $opt_ variables

    # Defaults
    test -z "$opt_help" && opt_help=0
    test -z "$opt_app_path" && opt_app_path=$app_path_default

    test "$opt_help" -eq 1 && die_show_help
}


main "$@"; exit
