#!/bin/sh

function log_msg() {
    local msg="$1"
    local tag="rosp-backend"

    logger -t "$tag" "$msg"
}

function backend_begin()
{
    local sup_pid=""

    log_msg "backend_begin"

    # wait for the latest dpkg to exit
    while fuser /var/lib/dpkg/lock >/dev/null 2>&1; do
        log_msg "dpkg lock is held, waiting....."
        sleep 1
    done
    while fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1; do
        log_msg "dpkg lock-frontend is held, waiting....."
        sleep 1
    done

    # stop the sysupgrade when we're running
    sup_pid="`ps aux|grep "usr/bin/sysupgrade "|grep -v grep|awk '{print $2}'`"
    # the sysupgrade script is not stopped, so stop it
    if [ ! -z "${sup_pid}" ] && [ ${sup_pid} -gt 0 ] &&
       [[ "`grep "State" /proc/${sup_pid}/status |awk -F' ' '{print $2}'`" != "T" ]]; then
        log_msg "stopping sysupgrade..."
        kill -STOP ${sup_pid}
        return 1
    fi

    log_msg "backend_begin end without stopping sysupgrade"
    return 0
}

function backend_complete()
{
    local stp=$1
    local sup_pid="`ps aux|grep "usr/bin/sysupgrade "|grep -v grep|awk '{print $2}'`"

    if [ ! -z "${sup_pid}" ] && [ ${sup_pid} -gt 0 ] && [ ${stp} -eq 1 ]; then
        log_msg "resume sysupgrade..."
        kill -CONT "-${sup_pid}"
    fi

    log_msg "backend_complete end"
}

function wait_dpkg_lock()
{
    # wait for the latest dpkg to exit
    while fuser /var/lib/dpkg/lock >/dev/null 2>&1; do
        log_msg "dpkg lock is held, waiting....."
        sleep 1
    done
    while fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1; do
        log_msg "dpkg lock-frontend is held, waiting....."
        sleep 1
    done
}

function resume_process()
{
    local stp=$1

    if [ ! -z "${stp}" ]; then
        log_msg "resume process..., PID: ${stp}"
        kill -CONT "-${stp}"
    fi
}

function find_parent_process_pid()
{
    local target_pname="$1"
    if [ -z "$target_pname" ]; then
        log_msg "Error: target process name not provided to find_parent_process_pid."
        echo ""
        return 1
    fi

    local pid_iterator=$$
    local final_found_pid=""
    local ppid
    local pname

    # Continue loop while pid_iterator is not 1 (init process)
    while [ "$pid_iterator" -ne 1 ]; do
        # Get parent PID of pid_iterator
        ppid=$(ps -o ppid= -p "$pid_iterator" | sed 's/ //g')

        # If ppid is empty (e.g. pid_iterator process disappeared or ps command failed)
        # cannot continue searching upwards, break loop
        if [ -z "$ppid" ]; then
            break
        fi

        # Get name of parent process (ppid)
        pname=$(ps -o comm= -p "$ppid" | sed 's/ //g')

        # If parent process name matches target name
        if [ "$pname" = "$target_pname" ]; then
            final_found_pid="$ppid"
        fi

        # If this parent process (ppid) is init process (PID 1)
        if [ "$ppid" -eq 1 ]; then
            break
        fi

        pid_iterator="$ppid"
    done

    local sup_pid="${final_found_pid}"

    if [ -z "${sup_pid}" ]; then
        log_msg "Parent process ${target_pname} not found in ancestry."
    else
        log_msg "Find parent process ${target_pname}, PID: ${sup_pid}"
    fi

    echo "${sup_pid}"
    return 0
}

function stop_process()
{
    local pid_to_stop="$1"
    local process_name="$2"
    local i
    local current_state
    local max_wait=5

    if [ -z "${pid_to_stop}" ]; then
        log_msg "stop_process: PID not provided."
        return 1 # Indicate failure or invalid input
    fi

    if [ ! -d "/proc/${pid_to_stop}" ]; then
        log_msg "stop_process: Process with PID ${pid_to_stop} not found."
        return 1
    fi

    current_state=$(awk '/State:/ {print $2}' /proc/${pid_to_stop}/status 2>/dev/null)
    if [ "${current_state}" = "T" ]; then
        log_msg "stop_process: Process ${process_name:-PID ${pid_to_stop}} is already stopped or traced."
        return 2 # Indicate already stopped
    fi

    log_msg "stop_process: Stopping ${process_name:-process with PID ${pid_to_stop}}."
    kill -STOP ${pid_to_stop}
    if [ $? -eq 0 ]; then
        # Wait until the process is actually stopped (state 'T'), to avoid races.
        for i in $(seq 1 ${max_wait}); do
            if [ ! -d "/proc/${pid_to_stop}" ]; then
                log_msg "stop_process: Process ${process_name:-PID ${pid_to_stop}} disappeared while waiting for stop."
                return 1
            fi
            current_state=$(awk '/State:/ {print $2}' /proc/${pid_to_stop}/status 2>/dev/null)
            if [ "${current_state}" = "T" ]; then
                log_msg "stop_process: Process ${process_name:-PID ${pid_to_stop}} is now stopped."
                return 0 # Indicate success
            fi
            sleep 1
        done
        log_msg "stop_process: Timeout waiting for ${process_name:-PID ${pid_to_stop}} to stop."
        return 1
    else
        log_msg "stop_process: Failed to send SIGSTOP to ${process_name:-PID ${pid_to_stop}}."
        return 1 # Indicate failure
    fi
}

function resume_process_and_parents()
{
    local pid_to_resume="$1"
    local current_pid
    local ppid
    local parent_state

    if [ -z "${pid_to_resume}" ]; then
        log_msg "resume_process_and_parents: PID not provided."
        return 1
    fi

    if [ ! -d "/proc/${pid_to_resume}" ]; then
        log_msg "resume_process_and_parents: Process with PID ${pid_to_resume} not found."
        return 1
    fi

    log_msg "resume_process_and_parents: Resuming process PID ${pid_to_resume}."

    kill -CONT "${pid_to_resume}"
    if [ $? -ne 0 ]; then
        log_msg "resume_process_and_parents: Failed to send SIGCONT to PID ${pid_to_resume}."
    fi

    current_pid="${pid_to_resume}"

    # Loop to resume parent processes
    while [ "${current_pid}" -ne 1 ] && [ -n "${current_pid}" ]; do
        ppid=$(ps -o ppid= -p "${current_pid}" | sed 's/ //g')

        if [ -z "${ppid}" ] || [ "${ppid}" -eq 1 ]; then
            break
        fi

        if [ ! -d "/proc/${ppid}" ]; then
            break
        fi

        parent_state=$(awk '/State:/ {print $2}' "/proc/${ppid}/status" 2>/dev/null)

        if [ "${parent_state}" = "T" ]; then
            log_msg "resume_process_and_parents: Parent PID ${ppid} is stopped. Resuming it."
            kill -CONT "${ppid}"
            if [ $? -ne 0 ]; then
                log_msg "resume_process_and_parents: Failed to send SIGCONT to parent PID ${ppid}."
            fi
        else
            break
        fi

        current_pid="${ppid}"
    done

    log_msg "resume_process_and_parents: Finished attempting to resume PID ${pid_to_resume} and its parents."
    return 0
}
