#!/bin/bash

wait_for_key() {
    read -rsp $'Press any key to continue...\n' -n1 key
}

enable_ssh() {
    echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
    sed -i '/AllowAgentForwarding/s/^#//g' /etc/ssh/sshd_config
    sed -i '/AllowTcpForwarding/s/^#//g' /etc/ssh/sshd_config
    /etc/init.d/S50sshd restart
    echo "SSH access is enabled at: $(ip addr show eth0 | awk '$1 == "inet" {gsub(/\/.*$/, "", $2); print "root@"$2}')"; 
}

if [ -n "$keymap" ]; then
    loadkeys $keymap;
fi

echo "Imaging mode is $imaging_mode"
sleep 5

echo "Making sure different version of parted use the right shared objects" 
/usr/bin/patchelf --remove-needed /usr/lib64/libparted.so.2 /usr/sbin/parted
/usr/bin/patchelf --add-needed /usr/lib64/libparted.so.2.0.5 /usr/sbin/parted

/usr/bin/patchelf --remove-needed /usr/lib64/libparted.so.2 /usr/sbin/parted32parted
/usr/bin/patchelf --add-needed /usr/lib64/libparted.so.2.0.1 /usr/sbin/parted32parted


if [ "$debug_mode" == "1" ]; then
    echo "Debug mode is on, dropping to shell, imaging process will continue when you leave shell";
    echo "Network testing tools available: run 'network-test --help' for speed testing";
    enable_ssh
    if [ -t 1 ]; then
        /bin/sh
    else
        echo "Not running in a terminal. Job control is not available."
    fi
fi

export PYTHONPATH=/

if [ "$imaging_mode" = "master" ]; then
        /usr/bin/python3 -m filewave.netboot
        wait_for_key

        poweroff -f
elif [ "$imaging_mode" = "image" ]; then
        /usr/bin/python3 -m filewave.bootup
        if [ $? -ne 0 ]; then
            wait_for_key
        fi

        reboot -f
else
        echo "Unknown imaging mode, dropping to shell"
        if [ -t 1 ]; then
            /bin/sh
        else
            echo "Not running in a terminal. Job control is not available."
        fi
fi

reboot -f
