#!/bin/sh

# Contact: Pekka Lundstrom  <pekka.lundstrom@jollamobile.com>
#
# Copyright (c) 2014, Jolla Ltd.
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the <organization> nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# This waits that user session has started within timeout
# This also keeps eye on need for SUW user session restart

do_restart() {
    # Try to start user session max two times

    let RESTARTS=$RESTARTS+1
    if [ $RESTARTS -ge 2 ]; then
        echo "Max restart tries done, giving up"
        echo "$USER_SERVICE failed to start"
        # TODO: What should we do? reboot?
        # At the moment we just exit here with error code
        # That is safe in case that if session actually
        # started after timeout. Our fail exit will cause only
        # start-user-session.service to fail, nothing else
        exit 1
    fi
    echo "Trying restart  $USER_SERVICE"
    systemctl --no-block restart $USER_SERVICE
    sleep 5
    WAIT=0
}

wait_user_service_to_start() {
    # This waits until user-session has started

    local ST=""
    local WAIT=0

    while [ 1 ]; do
        echo "In wait loop ($WAIT)"
        ST=$(systemctl is-active $USER_SERVICE)
        if [ "$ST" == "active" ]; then
            return 0
        elif [ "$ST" == "activating" ]; then
            sleep 1
        elif [ "$ST" == "unknown" ]; then
            # service should go to "activating" state very soon
            # wait max 3 seconds
            if [ $WAIT -lt 3 ]; then
                sleep 1
            else
                echo "$USER_SERVICE did not try to start"
                do_restart
            fi
        else
            echo "$USER_SERVICE failed to start, status = $ST"
            do_restart
        fi
        let WAIT=$WAIT+1
        if [ $WAIT_TIMEOUT -gt 0 -a $WAIT -gt $WAIT_TIMEOUT ]; then
            echo "$USER_SERVICE start timeout"
            do_restart
        fi
    done
}


# ------------------ main() -----------------------

# User id comes as $1 or we look for it
if [ -n "$1" ]; then
    DEF_UID=$1
else
    DEF_UID=$(grep "^UID_MIN" /etc/login.defs |  tr -s " " | cut -d " " -f2)
fi
USER_SERVICE=user\@${DEF_UID}.service
UNAME=$(getent passwd $DEF_UID | cut -d ":" -f1)
NORMAL_TIMEOUT=45
RESTARTS=0

# Select timeout for start. Normally we have timeout
# but if SUW language selection has not yet run then
# SUW than hold start forever. No timeout in that case
if [ -f /home/${UNAME}/.jolla-startupwizard-done ]; then
    WAIT_TIMEOUT=$NORMAL_TIMEOUT
else
    WAIT_TIMEOUT=0
fi

wait_user_service_to_start
echo "$USER_SERVICE started"
exit 0
