#!/bin/sh
#
# Copyright (C) 2019  Etersoft
# Copyright (C) 2019  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

serv_edit()
{
    local SERVICE="$1"
    shift

    case $SERVICETYPE in
        systemd)
            # editing only a drop-in is pointless for a unit that already lives in
            # /etc/systemd/system, so edit the full file there (unless args given)
            if [ -z "$*" ] ; then
                case "$($SYSTEMCTL show -p FragmentPath "$SERVICE" 2>/dev/null | sed -e 's|.*=||')" in
                    /etc/systemd/system/*)
                        set -- --full
                        ;;
                esac
            fi

            # remember if the service is running, to apply the change afterwards
            local wasactive=''
            $SYSTEMCTL is-active --quiet "$SERVICE" 2>/dev/null && wasactive=1

            # systemctl edit is interactive and uses $SYSTEMD_EDITOR/$EDITOR/$VISUAL;
            # sudo resets the environment, so preserve those across it
            local sudoenv=''
            [ "$SYSTEMCTL_RUNNER" = "docmd" ] || set_sudo
            case "$SUDO" in
                sudo*) sudoenv='--preserve-env=SYSTEMD_EDITOR,EDITOR,VISUAL' ;;
            esac

            # systemctl edit reloads the systemd manager (daemon-reload) by itself
            docmd $SUDO $sudoenv $SYSTEMCTL edit "$@" "$SERVICE" || return

            # the new unit settings take effect only after a restart
            if [ -n "$wasactive" ] ; then
                info "Restarting $SERVICE to apply the changes ..."
                run_systemctl restart "$SERVICE"
            fi
            ;;
        *)
            fatal "Have no suitable for $DISTRNAME command for $SERVICETYPE"
            ;;
    esac
}
