#!/bin/bash

# Create a dedicated systemd config
#
# usage: ynh_add_systemd_config [--service=service] [--template=template]
# | arg: -s, --service=     - Service name (optionnal, `$app` by default)
# | arg: -t, --template=    - Name of template file (optionnal, this is 'systemd' by default, meaning `../conf/systemd.service` will be used as template)
#
# This will use the template `../conf/<templatename>.service`.
#
# See the documentation of `ynh_add_config` for a description of the template
# format and how placeholders are replaced with actual variables.
#
# Requires YunoHost version 4.1.0 or higher.
ynh_add_systemd_config() {
    # Declare an array to define the options of this helper.
    local legacy_args=stv
    local -A args_array=([s]=service= [t]=template=)
    local service
    local template
    # Manage arguments with getopts
    ynh_handle_getopts_args "$@"
    service="${service:-$app}"
    template="${template:-systemd.service}"

    ynh_add_config --template="$template" --destination="/etc/systemd/system/$service.service"

    systemctl enable $service --quiet
    systemctl daemon-reload
}

# Remove the dedicated systemd config
#
# usage: ynh_remove_systemd_config [--service=service]
# | arg: -s, --service=     - Service name (optionnal, $app by default)
#
# Requires YunoHost version 2.7.2 or higher.
ynh_remove_systemd_config() {
    # Declare an array to define the options of this helper.
    local legacy_args=s
    local -A args_array=([s]=service=)
    local service
    # Manage arguments with getopts
    ynh_handle_getopts_args "$@"
    local service="${service:-$app}"

    local finalsystemdconf="/etc/systemd/system/$service.service"
    if [ -e "$finalsystemdconf" ]; then
        ynh_systemd_action --service_name=$service --action=stop
        systemctl disable $service --quiet
        ynh_secure_remove --file="$finalsystemdconf"
        systemctl daemon-reload
    fi
}

# Start (or other actions) a service,  print a log in case of failure and optionnaly wait until the service is completely started
#
# usage: ynh_systemd_action [--service_name=service_name] [--action=action] [ [--line_match="line to match"] [--log_path=log_path] [--timeout=300] [--length=20] ]
# | arg: -n, --service_name= - Name of the service to start. Default : `$app`
# | arg: -a, --action=       - Action to perform with systemctl. Default: start
# | arg: -l, --line_match=   - Line to match - The line to find in the log to attest the service have finished to boot. If not defined it don't wait until the service is completely started.
# | arg: -p, --log_path=     - Log file - Path to the log file. Default : `/var/log/$app/$app.log`
# | arg: -t, --timeout=      - Timeout - The maximum time to wait before ending the watching. Default : 300 seconds.
# | arg: -e, --length=       - Length of the error log displayed for debugging : Default : 20
#
# Requires YunoHost version 3.5.0 or higher.
ynh_systemd_action() {
    # Declare an array to define the options of this helper.
    local legacy_args=nalpte
    local -A args_array=([n]=service_name= [a]=action= [l]=line_match= [p]=log_path= [t]=timeout= [e]=length=)
    local service_name
    local action
    local line_match
    local length
    local log_path
    local timeout
    # Manage arguments with getopts
    ynh_handle_getopts_args "$@"
    service_name="${service_name:-$app}"
    action=${action:-start}
    line_match=${line_match:-}
    length=${length:-20}
    log_path="${log_path:-/var/log/$service_name/$service_name.log}"
    timeout=${timeout:-300}

    # Manage case of service already stopped
    if [ "$action" == "stop" ] && ! systemctl is-active --quiet $service_name; then
        return 0
    fi

    # Start to read the log
    if [[ -n "$line_match" ]]; then
        local templog="$(mktemp)"
        # Following the starting of the app in its log
        if [ "$log_path" == "systemd" ]; then
            # Read the systemd journal
            journalctl --unit=$service_name --follow --since=-0 --quiet >"$templog" &
            # Get the PID of the journalctl command
            local pid_tail=$!
        else
            # Read the specified log file
            tail --follow=name --retry --lines=0 "$log_path" >"$templog" 2>&1 &
            # Get the PID of the tail command
            local pid_tail=$!
        fi
    fi

    # Use reload-or-restart instead of reload. So it wouldn't fail if the service isn't running.
    if [ "$action" == "reload" ]; then
        action="reload-or-restart"
    fi

    local time_start="$(date --utc --rfc-3339=seconds | cut -d+ -f1) UTC"

    # If the service fails to perform the action
    if ! systemctl $action $service_name; then
        # Show syslog for this service
        ynh_exec_err journalctl --quiet --no-hostname --no-pager --lines=$length --unit=$service_name
        # If a log is specified for this service, show also the content of this log
        if [ -e "$log_path" ]; then
            ynh_exec_err tail --lines=$length "$log_path"
        fi
        ynh_clean_check_starting
        return 1
    fi

    # Start the timeout and try to find line_match
    if [[ -n "${line_match:-}" ]]; then
        set +x
        local i=0
        local starttime=$(date +%s)
        for i in $(seq 1 $timeout); do
            # Read the log until the sentence is found, that means the app finished to start. Or run until the timeout
            if [ "$log_path" == "systemd" ]; then
                # For systemd services, we in fact dont rely on the templog, which for some reason is not reliable, but instead re-read journalctl every iteration, starting at the timestamp where we triggered the action
                if journalctl --unit=$service_name --since="$time_start" --quiet --no-pager --no-hostname | grep --extended-regexp --quiet "$line_match"; then
                    ynh_print_info --message="The service $service_name has correctly executed the action ${action}."
                    break
                fi
            else
                if grep --extended-regexp --quiet "$line_match" "$templog"; then
                    ynh_print_info --message="The service $service_name has correctly executed the action ${action}."
                    break
                fi
            fi
            if [ $i -eq 30 ]; then
                echo "(this may take some time)" >&2
            fi
            # Also check the timeout using actual timestamp, because sometimes for some reason,
            # journalctl may take a huge time to run, and we end up waiting literally an entire hour
            # instead of 5 min ...
            if [[ "$(( $(date +%s) - $starttime))" -gt "$timeout" ]]
            then
                i=$timeout
                break
            fi
            sleep 1
        done
        set -x
        if [ $i -ge 3 ]; then
            echo "" >&2
        fi
        if [ $i -eq $timeout ]; then
            ynh_print_warn --message="The service $service_name didn't fully executed the action ${action} before the timeout."
            ynh_print_warn --message="Please find here an extract of the end of the log of the service $service_name:"
            ynh_exec_warn journalctl --quiet --no-hostname --no-pager --lines=$length --unit=$service_name
            if [ -e "$log_path" ]; then
                ynh_print_warn --message="\-\-\-"
                ynh_exec_warn tail --lines=$length "$log_path"
            fi
        fi
        ynh_clean_check_starting
    fi
}

# Clean temporary process and file used by ynh_check_starting
#
# [internal]
#
# Requires YunoHost version 3.5.0 or higher.
ynh_clean_check_starting() {
    if [ -n "${pid_tail:-}" ]; then
        # Stop the execution of tail.
        kill -SIGTERM $pid_tail 2>&1
    fi
    if [ -n "${templog:-}" ]; then
        ynh_secure_remove --file="$templog" 2>&1
    fi
}