#!/bin/sh

# Contact: Pekka Lundstrom  <pekka.lundstrom@jollamobile.com>
#
# Copyright (c) 2013-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.

# /sbin/preinit
# This is run before init. It will do tricks needed before starting actual init
# and once done, it will start systemd.
#

echo_g()
{
    [ -r /proc/uptime ] && read uptime idletime < /proc/uptime
    echo "preinit: ($uptime) $@"
}

check_interactive_startup() {
    echo_g "Press Return key for interactive startup"
    read -n1 -t1
    if [ $? -eq 0 ]; then
        show_menu
    fi
}


show_menu()
{
    while [ true ]; do
        echo ""
        echo "Choose bootup option:"
        echo "  1) Boot USER"
        echo "  2) Boot ACT_DEAD"
        echo "  3) Boot TEST"
        echo "  5) Factory Clear"
        echo "  7) Reboot"
        echo "  9) Start a shell"
        echo ""

        read -t10 selection
        if [ $? -ne 0 ]; then
            echo_g "Timeout, boot continues"
            return
        fi
        case "$selection" in
        1)
            boot "USER"
            ;;
        2)
            boot "ACT_DEAD"
            ;;
        3)
            boot "TEST"
            ;;
        5)
            /usr/sbin/clear-device
            ;;
        7)
            reboot_with_same_reason
            ;;
        9)
            start_shell
            ;;
        *)
            echo_g "Invalid selection"
            ;;
        esac
    done
}

start_shell() {
    tty=`grep "tty" /proc/consoles | head -1 | cut -d " " -f 1`
    if [ -z "$tty" ] ; then
        tty=ttyS0
    fi
    mount /home
    echo_g "Starting shell at $tty"
    /sbin/agetty 115200 $tty -n -l /bin/sh
}

disable_watchdog() {
    if [ -c /dev/watchdog ] && [ -w /dev/watchdog ]; then
        echo "V" > /dev/watchdog
        echo_g "\"Magic Close\" /dev/watchdog with character 'V'"
    fi
}

check_bootchartd() {
    if [ -f /etc/bootchartd.active -a -x /lib/systemd/systemd-bootchart ]; then
        # Before starting remove older bootcharts, keep 4 most recent ones
        ls -1tr /var/log/bootchart-* | head -n-4 | xargs rm -f
        echo_g "Activating bootchartd because of /etc/bootchartd.active"
        /lib/systemd/systemd-bootchart &
    fi
}

do_minimal_mounts() {
    # Mount bare minimum
    /bin/mount -t proc none /proc
    /bin/mount -t sysfs none /sys
    if ! grep -q devtmpfs /proc/mounts; then
        /bin/mount -t devtmpfs devtmpfs /dev
    fi
    # Ensure rootfs is mounted as RW
    /bin/mount -o remount,rw / ||  echo_g "Can't remount / as rw"
    # Set no oom killing
    echo -1000 > /proc/self/oom_score_adj
}

SAVED_BOOTSTATE_FILE=/.preinit-saved_bootstate

save_bootstate() {
    # Save bootstate so we can boot to correct mode  after reboot
    # Don't overwrite if we have saved it already.
    # During factory reset we do two reboots in a row and
    # must use original reason
    [ -f $SAVED_BOOTSTATE_FILE ] && return 0
    find_bootstate
    /bin/echo $BOOTSTATE  > $SAVED_BOOTSTATE_FILE
    echo_g "Saved bootstate $BOOTSTATE"
}

get_saved_bootstate() {
    # If bootstate was saved, get it back
    if [ -f $SAVED_BOOTSTATE_FILE ]; then
        read BOOTSTATE < $SAVED_BOOTSTATE_FILE && return 0
    fi
    return 1
}

forget_saved_bootstate() {
    # Clear saved bootstate so it won't hunt us later
    if [ -f $SAVED_BOOTSTATE_FILE ]; then
        /bin/rm -f $SAVED_BOOTSTATE_FILE
    fi
}

reboot_with_same_reason() {
    # Reboot the device and remember the bootup reason so
    # after reboot we boot with same status
    save_bootstate
    /bin/sync
    echo_g "reboot -f"
    /usr/sbin/reboot -f
    # have this as backup if reboot didn't work
    /bin/echo b > /proc/sysrq-trigger
}

PLUGIN_PATH=/usr/lib/startup/preinit

run_plugin() {
    # This will run preinit-plugin named in $1
    # preinit-plugins need to be installed in /usr/lib/startup/preinit
    # and have x permission for root
    # If plugin does not exist, error (1) is returned
    # $2 (optional) is name of the variable used to capture output of the plugin
    # Return value from plugin is returned by this function
    # Example:
    # run_plugin test_wipe WIPE_NEEDED
    # will run /usr/lib/startup/preinit/test_wipe and save output to $WIPE_NEEDED
    # return value of this function will be what ever /usr/lib/startup/preinit/test_wipe returned

    local plugin_output=""
    local ret=0
    [ -z "$1" ] && echo_g "ERROR: plugin name missing" && return 1
    if [ -x ${PLUGIN_PATH}/$1 ]; then
        plugin_output=$(${PLUGIN_PATH}/$1)
        ret=$?
        echo "$1: $plugin_output : $ret"
    else
        # Plugin is not there, output warning
        echo_g "WARNING: plugin ${PLUGIN_PATH}/$1 not found"
        plugin_output=""
        ret=1
    fi
    [ -n "$2" ] && eval "$2=\"$plugin_output\""
    return $ret
}

run_plugin_dir() {
    # This runs all executable files that are found in dir $PLUGIN_PATH/$1
    # Plugins are run in alfapethical order
    cd ${PLUGIN_PATH}
    BINARIES=$(find $1 -maxdepth 1 -perm -700 | sort)
    for SCRIPTLET in $BINARIES; do
        [ -d $SCRIPTLET ] || run_plugin $SCRIPTLET
    done
    cd - > /dev/null
}

check_phone_wipeout() {
    # This will check if we need to restore phone settings and or sw.
    local FACTORY_COMMAND=0 
    local REBOOT_AFTER_FACTORY_RESET=0

    run_plugin is_erase_needed WIPE_MODE
    if [ "$WIPE_MODE" == "TOTAL_ERASE_FACTORY" ]; then
        WIPE_MODE="TOTAL_ERASE"
        FACTORY_COMMAND=1
    fi

    if [ -f /usr/share/lipstick/devicelock/.clear-device-enable-reboot ]; then
        REBOOT_AFTER_FACTORY_RESET=1
    fi

    if [ "$WIPE_MODE" == "TOTAL_ERASE" ]; then
        echo_g "Phone total erase requested"
        # Before doing the actual clean, make sure total erase is supported
        if run_plugin is_total_erase_supported; then
            # First clear possible pending RTC alarms
            dsmetool --clear-rtc
            # Then do erase
            if run_plugin erase_device; then
                echo_g "Total erase done"
                run_plugin clear_total_erase_request
                # If this was started at factory via kernel cmdline, we can boot
                # to TEST mode. Othwerwise we poweroff
                if [ $FACTORY_COMMAND -eq 1 ]; then
                    BOOTSTATE="TEST"
                    boot "TEST"
                    # Note that at this point device will go to TEST mode using
                    # current rootfs, not with factory snapshot.
                    # But that is intentional. It is more important to boot fast
                    # into TEST mode and this makes also sure that first user boot
                    # happens with factory snapshot
                fi
                sync
                if [ $REBOOT_AFTER_FACTORY_RESET -eq 1 ]; then
                    echo_g "Reboot"
                    reboot -f
                    # have this as backup if reboot didn't work
                    echo b > /proc/sysrq-trigger
                else
                    echo_g "Poweroff"
                    poweroff -f
                    # have this as backup if poweroff didn't work
                    echo o > /proc/sysrq-trigger
                fi
                # should never get this far. Crash kernel to get attention
                exit 1
            fi
        fi
        echo_g "ERROR: Total erase failed or is not supported"
        run_plugin clear_total_erase_request
    elif [ "$WIPE_MODE" == "SETTINGS_ERASE" ]; then
        echo_g "Settings clear requested"
        if run_plugin erase_settings; then
            echo_g "Settings cleared"
        else
            echo_g "ERROR: Settings erase failed or not supported"
       fi
       run_plugin clear_settings_erase_request
    elif [ "$WIPE_MODE" == "POST_ERASE_CLEANING" ]; then
        echo_g "Doing post erase clean up"
        if run_plugin do_post_cleaning; then
            echo_g "Cleaning done, must reboot before continuing "
            reboot_with_same_reason
        fi
    fi
}

run_preinit_oneshot() {
    # This runs scripts added to system by "add-preinit-oneshot"
    # Links to scripts are located in /etc/oneshot.d/preinit directory
    # After succesfull run link is removed
    # If run fails, script is renamed <name>.failed, converted to normal file
    # and contents is previous link

    LINKS=$(/bin/find /etc/oneshot.d/preinit/ -maxdepth 1 -type l)
    if [ -n "$LINKS" ]; then
        echo_g "Must run oneshot"
        for SCRIPTLET in $LINKS; do
            OK=0
            $SCRIPTLET && OK=1
            if [ $OK -eq 1 ]; then
                rm $SCRIPTLET 
                echo_g "oneshot: $SCRIPTLET - OK" 
            else
                echo_g "oneshot: $SCRIPTLET - FAIL"
                # Convert link to normal file with .failed extension
                # and content is previous link
                readlink $SCRIPTLET > ${SCRIPTLET}.failed
                rm $SCRIPTLET
            fi
        done
        echo_g "Reboot after oneshot"
        reboot_with_same_reason
    fi
}

find_bootstate() {
    # What mode should we boot?
    # Default to USER

    run_plugin get_bootstate BOOTSTATE
    [ -z "$BOOTSTATE" ] && BOOTSTATE="USER"
}

boot() {
    # Boot to given mode ($1)  or find out 
    local startup_target=""
    if [ -n "$1" ]; then 
        BOOTSTATE=$1 
        echo_g "Bootstate $BOOTSTATE given"
    elif get_saved_bootstate; then
        echo_g "Using saved Bootstate $BOOTSTATE"
    else 
        find_bootstate
        echo_g "BOOTSTATE = $BOOTSTATE"
    fi
    forget_saved_bootstate

    if [ "$BOOTSTATE" == "USER" ]; then
        startup_target="default.target"
    elif [ "$BOOTSTATE" == "ACT_DEAD" ]; then
        startup_target="actdead.target"
    elif [ "$BOOTSTATE" == "TEST" ]; then
        startup_target="factory-test.target"
    fi
    # Make sure we have the target file, if not go to default
    if [ -z "$startup_target" ] ||
       [ ! -f /lib/systemd/system/$startup_target ]; then
        echo_g "ERROR: Unknown bootmode $BOOTSTATE. Defaulting to USER"
        startup_target="default.target"
    fi
    ulimit -s 2048 # Restrict stack sizes to 2mb instead of 8mb
    echo_g "Booting to $startup_target"
    exec /lib/systemd/systemd --unit=$startup_target
}

##############  main() ###########################
export PATH=/sbin:/usr/sbin:/bin:/usr/bin
echo " "
eval `grep PRETTY_NAME /etc/os-release`
echo_g "Welcome to $PRETTY_NAME"
echo " "
do_minimal_mounts
disable_watchdog
check_bootchartd
run_plugin_dir early.d
check_interactive_startup
check_phone_wipeout
run_preinit_oneshot
run_plugin_dir late.d
boot
