#!/bin/bash
#
# .---.                  .              .
# |                      |              |
# |--- .--. .-.  .-.  .-.|  .-. .--.--. |.-.  .-. .--.  .-.
# |    |   (.-' (.-' (   | (   )|  |  | |   )(   )|  | (.-'
# '    '     --'  --'  -' -  -' '  '   -' -'   -' '   -  --'
#
#                    Freedom in the Cloud
#
# Final stage of install
#
# License
# =======
#
# Copyright (C) 2014-2016 Bob Mottram <bob@freedombone.net>
#
# 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/>.

function install_final {
    if [[ $(is_completed $FUNCNAME) == "1" ]]; then
        return
    fi
    # unmount any attached usb drive
    if [ -d $USB_MOUNT ]; then
        umount $USB_MOUNT
        rm -rf $USB_MOUNT
    fi
    function_check split_gpg_key_into_fragments
    split_gpg_key_into_fragments
    mark_completed $FUNCNAME
    clear
    echo ''

    echo $"
    *** ${PROJECT_NAME} installation is complete ***

    Ensure that ports are forwarded from your internet router
"
    echo ''

    if [ -f "/home/$MY_USERNAME/README" ]; then
        echo $"See /home/$MY_USERNAME/README for post-installation instructions."
        echo ''
    fi
    # add user menu on ssh login
    if ! grep -q 'control' /home/$MY_USERNAME/.bashrc; then
        echo 'control' >> /home/$MY_USERNAME/.bashrc
    fi
    if [ ! -f $IMAGE_PASSWORD_FILE ]; then
        if [ -f /root/${PROJECT_NAME}-wifi.cfg ]; then
            create_wifi_startup_script
            echo ''
            echo $'Shutting down the system. Detatch the ethernet cable, attach wifi dongle, then power on again.'
            echo ''
            shutdown now
            return
        fi
        reboot
    fi
}

function update_installed_apps_list {
    # Why does this secondary file exist, apart from COMPLETION_FILE ?
    # It's so that it is visible to unprivileged users from the user control panel
    cat $COMPLETION_FILE | grep "install_" > /usr/share/${PROJECT_NAME}/installed.txt
}

function setup_final {
    function_check update_installed_apps_list
    update_installed_apps_list

    function_check install_tripwire
    install_tripwire

    function_check install_final
    install_final

    export DEBIAN_FRONTEND=
}

# NOTE: deliberately no exit 0
