#!/bin/bash
# set -x

if test `id -u --name` != 'webapp' ; then
    # Note: `exec` will change the process group ID
    exec su --login webapp $0 -- "$@"  # since centos8, if not using --login, an umask of 077 is applied !
fi

main() {
    path_rce="/opt/plugandwork/apps/rce"
    path_shared="/opt/plugandwork/shared"
    path_packages="/opt/plugandwork/packages"

    parse_opts "$@"

    need_fix=0
    can_fix=0

    test ! -h "${path_rce}/current/log" -o \
        ! -h "${path_rce}/current/tmp" \
        && need_fix=1
        # ! -h "${path_rce}/current/config/puma.rb" -o \
        # ! -h "${path_rce}/current/config/config.yml" -o \
        # ! -h "${path_rce}/current/config/mongoid.yml" -o \
        # ! -h "${path_rce}/current/config/milvus.yml" -o \
        # ! -h "${path_rce}/current/config/redis.yml" \
        # ! -h "${path_rce}/current/config/sidekiq.yml" \
        # ! -h "${path_rce}/current/tmp/pids" -o \

    PATH=$PATH:/usr/sbin lsof -nP 2>/dev/null |grep -q "${path_rce}"
    test $? -ne 0 && can_fix=1

    if test $need_fix -ge 1 -a $can_fix -lt 1 -a $opt_force -lt 1; then
        >&2 echo "PAW symbolic links can not be fixed while files are used."
        >&2 echo "Please stop the application before"
        >&2 echo "for example:"
        >&2 echo "    sudo /usr/local/bin/prevent_autoremediation"
        >&2 echo "    paw_service stop paw.target"
        >&2 echo "    paw_service stop visio"
        >&2 echo "    paw_service stop puma"
        >&2 echo "    paw_service stop resque"
        >&2 echo "    paw_service stop resque-scheduler"
        >&2 echo "    paw_service stop sidekiq"
        >&2 echo "    paw_service status"
        >&2 echo "    kill_orphaned_resque"
        >&2 echo "    $0"
        >&2 echo "    paw_restart"
        >&2 echo "    sudo /usr/local/bin/resume_autoremediation"
        >&2 echo
        >&2 echo "Note that there may still be rogue Resque workers remaining which you can kill with (beware not to kill yourself by cd out of ${path_rce} !)"
        >&2 echo "    kill_orphaned_resque"
        >&2 echo "    PATH=$PATH:/usr/sbin lsof -nP |grep ${path_rce} |ruby -ane '"'next if $F[1] !~ /\d/; Process.kill("TERM", $F[1].to_i)'"'"
        die
    fi

    if test $need_fix -ge 1 -a \( $can_fix -ge 1 -o $opt_force -ge 1 \); then
        # test -e "${path_rce}/current/log" && rm -r "${path_rce}/current/log"
        # test -e "${path_rce}/current/tmp" && rm -r "${path_rce}/current/tmp"
        rm -r "${path_rce}"/current/{log,tmp} 2>/dev/null

        ln -s "${path_shared}/log" "${path_rce}/current/log"
        ln -s "${path_shared}/tmp" "${path_rce}/current/tmp"

        # Done in Puppet
        # ln -s "${path_shared}/pids" "${path_rce}/current/tmp/pids"

        # for f in `ls -1 /opt/plugandwork/config/*.{yml,rb} 2>/dev/null | xargs -r -n1 basename`; do
        #     rm "${path_rce}/current/config/$f" 2>/dev/null
        #     ln -s "/opt/plugandwork/config/$f" "${path_rce}/current/config/$f"
        # done

        # for f in `ls -1 /opt/plugandwork/config/services/*.{service,target} 2>/dev/null | xargs -r -n1 basename`; do
        #     rm "${path_rce}/current/services/$f" 2>/dev/null
        #     ln -s "/opt/plugandwork/config/services/$f" "${path_rce}/current/services/$f"
        # done
    fi

    # test -e "${path_rce}/current/config/mongodb.yml" && rm "${path_rce}/current/config/mongodb.yml"
    # test -e "${path_rce}/current/config/thin.yml" && rm "${path_rce}/current/config/thin.yml"

    # Done in Puppet
    # chmod -R 770 "${path_rce}/current/tmp" "${path_shared}/tmp"

    test -d "${path_shared}"/public_front-save && rsync -aW --delete "${path_shared}"/public_front-save/ "${path_rce}"/current/public/front/

    # echo -e "Add symlinks for potential packages..."
    nb_packages=$(find ${path_packages} -maxdepth 1 ! -path ${path_packages} -type d | wc -l)
    if [ "$nb_packages" -gt 0 ]; then
        packages=$(find ${path_packages} -maxdepth 1 ! -path ${path_packages} -type d | xargs readlink -f)
        for package_full_path in $packages; do
            package_short_name=$(basename $package_full_path)
            test -L "${path_rce}/current" && mkdir -p "${path_rce}/current/packages"
            # echo -e "Linking ${path_rce}/current/packages/$package_short_name to $package_full_path"
            # test -e "${path_rce}/current/packages/$package_short_name" && rm -r "${path_rce}/current/packages/$package_short_name"
            ln -sf "$package_full_path" "${path_rce}/current/packages/$package_short_name"
        done
    fi
    # echo -e "Add symlinks for packages done !"

    return 0
}


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


die_show_help() {
    show_help
    exit 2
}


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


parse_opts() {
    # AF: Put the short version of argument after |
    # http://perldoc.perl.org/Getopt/Long.html
    parsed_opts=$(
    perl -MGetopt::Long -le '
        @options = (
        "force!",
        "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_force" && opt_force=0

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


main "$@"; exit
