#!/bin/bash
# Copyright (C) 2025 CEA - All Rights Reserved
# 
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU 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 General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.


SCRIPT_DIR="$(realpath "$(dirname "$0")")"

if [ "$(id -u)" != "0" ]; then
   echo "[!] This script must be run as root" 1>&2
   echo "Usage : sudo $0 " 1>&2
   exit 1
fi

# This cross-compilation toolchain was obtained by running `make sdk` inside the `embedded-device/buildroot/` directory. 
# The SDK archive contains the Buildroot-generated toolchain required for cross-compiling code for the target embedded system.
TOOLCHAIN="arm-buildroot-linux-gnueabihf_sdk-buildroot"
TOOLCHAIN_TAR="$TOOLCHAIN.tar.xz"
echo "[+] Extracting the Mirai cross-compilation toolchain."
cd "$SCRIPT_DIR/../mirai_setup"
if [ -d "$TOOLCHAIN" ]; then
    echo "[+] Toolchain directory '$TOOLCHAIN' already exists. Skipping extraction."

elif [ -f "$TOOLCHAIN_TAR" ]; then
    sleep 1
    tar -xvJf "$TOOLCHAIN_TAR"
    if [ $? -ne 0 ]; then
        echo "[!] Error: Failed to extract $TOOLCHAIN_TAR."
        exit 1
    fi

else
    echo "[!] Error: Could not find '$TOOLCHAIN' directory nor the archive $TOOLCHAIN_TAR in the '/mirai_setup' directory."
    exit 1
fi
cd "$TOOLCHAIN"
./relocate-sdk.sh


echo ""
echo "[+] Cloning and patching the Mirai source code."
sudo apt install -y git
cd "$SCRIPT_DIR"
./CloneMirai.sh
if [ $? -ne 0 ]; then
	echo "[!] Failed to clone or patch Mirai."
	exit 1
fi

echo ""
echo "[+] Starting the compilation of the Mirai source code."
cd "$SCRIPT_DIR/../mirai_setup/compilMirai"
./CompilMirai.sh "$SCRIPT_DIR/../mirai_setup/$TOOLCHAIN/bin"
if [ $? -ne 0 ]; then
	echo "[!] Failed to compilation the Mirai source code."
	exit 1
fi

echo ""
echo "[+] Installing the requirements for the DNS server."
sudo apt install -y bind9 bind9utils bind9-doc


echo ""
echo -e "[+] Installing the C&C Database."
cd ../Database
./installDB.sh


echo ""
echo "[+] Installation complete. You can now start the Mirai servers."