#!/bin/sh

# Copyright 2013 Israel Martín Escalona <imartin@entel.upc.edu>
# 
# This file is part of Wipos.
# 
# Wipos 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.
# 
# Wipos 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 Wipos.  If not, see <http://www.gnu.org/licenses/>.

function applyPatch(){
    echo -n "$1"
    
    #echo "patch -d $4 -p0 < patches/$2-$3.patch "
    if [ -e patches/$2-$3.patch ]; then
        patch -s -d $4 -p0 < patches/$2-$3.patch &>> $log_path && echo "[OK]"
    else
	echo "File patches/$2-$3.patch does not exists" >> $log_path
	return 1 
    fi
      
    exit_code="$?"
    #echo "code: $exit_code"
    if [ $exit_code -ne 0 ]; then 
	echo "Patch $2-$3.patch was not successfuly applied" >> $log_path
	return 1
    fi
    
    return 0;
}

function printUsage() {
    echo "USAGE: $1 [-p] [-v] -k kernel_path"
    echo "  p: Don't apply the patches for kernel sources (in the case they have been applied before)"
    echo "  v: Indicate the version of the kernel in which the platform is going to be deployed. It is used to select the proper patches"
    echo "  k: Indicate the path to the kernel sources which are going to be enhanced with positioning patches"
    echo "  t: Indicate the metric used for timestamping: 0 indicates CPU clocks [default] and 1 indicates nanoseconds"
    echo "  d: Install the platform with debug support"
    echo "  h: Prints this usage message" 
}

#kernel_path="$*"
debug=0
timestamping=0
apply_patches=1
version="latest" 
exec_filename="wifi_positioning_reader"
pos80211_loader="load_pos80211"
log_path="$(pwd)/log.txt"
batch_measurement="batch_measurement"
module="pos80211"

# Reading the parameters
while getopts ":dt:h:pt:v:k:" optname
  do
    case "$optname" in
      "p")
	apply_patches=0
        echo "Option $optname is specified"
        ;;
      "k")
        kernel_path="$OPTARG"
        echo "Option $optname has value $OPTARG"
        ;;
      "v")
        version="$OPTARG"
        echo "Option $optname has value $OPTARG"
        ;;  
      "t")
        if [ $OPTARG -ne 0 && $OPTARG -ne 1 ]; then echo "Option $optname initialized with a wrong value: $OPTARG"; exit; fi;
        timestamping="$OPTARG"
        echo "Option $optname has value $OPTARG"
        ;;
      "h")
        printUsage $0
        exit 1
        ;;
      "d")
	debug=1;
	echo "Debug activated!"
	;;
      "?")
        echo "Unknown option $OPTARG"
        ;;
      ":")
        echo "No argument value for option $OPTARG"
        ;;
      *)
      # Should not occur
        echo "Unknown error while processing options"
        ;;
    esac
  done

if [ -z "$kernel_path" ]; then
    printUsage $0
    exit 1
fi

# Cleaning previous log
if [ -e "log.txt" ]; then
    rm -f log.txt &> /dev/null
fi

# Running the script
echo "** Initialization of the installation process **"
echo 
echo "** Deploying the location platform to kernel version $version **"
echo 

echo "** Copying the additional files **"
echo -n "Updating MAC80211 sources.........."
cp kernel/mac80211/* "$kernel_path/net/mac80211/" &>> $log_path && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && echo "cp kernel/mac80211/* $kernel_path/net/mac80211/ &>> $log_path" && exit 1; fi

echo -n "Updating kernel includes.........."
cp -r kernel/include/* "$kernel_path/include" &>> $log_path && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && exit 1; fi

case $timestamping in
    "0" )
        cat kernel/include/positioning/globals.h | sed -e "/#define _COMPUTE_TIME_IN_NS_/d" | sed -e "/#define _COMPUTE_TIME_IN_CLOCKS_/c\#define _COMPUTE_TIME_IN_CLOCKS_" > "$kernel_path/include/positioning/globals.h" 
        ;;
    "1" )
        cat kernel/include/positioning/globals.h | sed -e "/#define _COMPUTE_TIME_IN_CLOCKS_/d" | sed -e "/#define _COMPUTE_TIME_IN_NS_/c\#define _COMPUTE_TIME_IN_NS_" > "$kernel_path/include/positioning/globals.h" 
        ;;
esac

mv "$kernel_path/include/positioning/globals.h" "$kernel_path/include/positioning/globals.h.bak" &>> $log_path
if [ $debug -eq 0 ]; then
    cat "$kernel_path/include/positioning/globals.h.bak" | sed -e "/#define _DEBUG_POSITIONING_/d" > "$kernel_path/include/positioning/globals.h" 
else
    cat "$kernel_path/include/positioning/globals.h.bak" | sed -e "/#define _DEBUG_POSITIONING_/c\#define _DEBUG_POSITIONING_" > "$kernel_path/include/positioning/globals.h" 
fi
rm "$kernel_path/include/positioning/globals.h.bak" &>> $log_path

if [ $apply_patches -ne 0 ]; then

    echo "** Applying the pathes for WiFi positioning **"

    for file in $(ls patches/*-${version}.patch)
    do 
        filename=`echo ${file%-*}`
        filename=`echo ${filename#*/}`
        applyPatch "Patching the ${filename} file.........." "${filename}" "$version" $kernel_path
        if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt"; cd $4; exit 1; fi
    done

#     applyPatch "Patching the agg-tx.c file.........." "agg-tx" "$version" $kernel_path
#     if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt"; cd $4; exit 1; fi
#     applyPatch "Patching the driver-ops.h file.........." "driver-ops" "$version" $kernel_path
#     if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt"; cd $4; exit 1; fi
#     applyPatch "Patching the sta_info.c file.........." "sta_info" "$version" $kernel_path
#     if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt"; cd $4; exit 1; fi
#     applyPatch "Patching the rx.c file.........." "rx" "$version" $kernel_path
#     if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt"; cd $4; exit 1; fi
#     applyPatch "Patching the tx.c file.........." "tx" "$version" $kernel_path
#     if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt"; cd $4; exit 1; fi
#     applyPatch "Patching the main.c file.........." "main" "$version" $kernel_path
#     if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt"; cd $4; exit 1; fi
#     applyPatch "Patching the Makefile file.........." "Makefile" "$version" $kernel_path
#     if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt"; cd $4; exit 1; fi
else
    echo "** Skipping the application of the pathes for WiFi positioning **"
fi
    
echo "** Positioning updates have been applied. Recompiling the kernel to make them available. **"
oldPath="`pwd`"
cd "$kernel_path"

mount /boot &>> $log_path
echo -n "Compiling the kernel......." && make &>> $log_path && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && cd "$oldPath" && exit 1; fi;
echo -n "Installing the modules......." && make modules_install &>> $log_path && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && cd "$oldPath" && exit 1; fi;
echo -n "Installing the new kernel......." && make install &>> $log_path && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && cd "$oldPath" && exit 1; fi;

echo "** Installation of the ${module} module **"

cp -r "${oldPath}/pos80211" /tmp &>> $log_path
cd "/tmp/pos80211" &>> $log_path

echo -n "Compiling the module ${module}......." && KDIR="$kernel_path" make -s clean &>> $log_path && KDIR="$kernel_path" make &>> $log_path && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && cd "$oldPath" && exit 1; fi;
echo -n "Installing the module ${module}......." && KDIR="$kernel_path" make -s install &>> $log_path && depmod -a &>> $log_path && KDIR="$kernel_path" make -s clean && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && cd "$oldPath" && exit 1; fi;

cat "${oldPath}/kernel/include/positioning/globals.h" | sed -e "/#define _COMPUTE_TIME_IN_CLOCKS_/d" | sed -e "s/\/\/#define _COMPUTE_TIME_IN_NS_/#define _COMPUTE_TIME_IN_NS_/" > ${kernel_path}/include/positioning/globals.h

cd "${oldPath}" &>> log_path
echo -n "Installing the script for loading the module (${pos80211_loader})......." && cat ./scripts/passive_tdoa | sed -e "s/#EXTERNAL_REDEFINITION_OF_MODULE_NAMES/#EXTERNAL_REDEFINITION_OF_MODULE_NAMES\nmodule=\"${module}\"/" > /usr/local/bin/$pos80211_loader && chmod 755 /usr/local/bin/$pos80211_loader && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && cd "$oldPath" && exit 1; fi;

echo "** Compiling/Linking the positining-sample reader **"
cd "${oldPath}/measurement_dumper"
echo -n "Generating the executable file......." && gcc -I../pos80211 -I../kernel/include -o $exec_filename measurement_dumper.c && chmod 755 $exec_filename && mv $exec_filename /usr/local/bin && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && cd "$oldPath" && exit 1; fi;

echo "** Installing the rest of the utilities **"
cd "$oldPath"
echo -n "Installing the script for running batch simulations (${batch_measurement}) ......." && cp ./scripts/read_distances /usr/local/bin/$batch_measurement && chmod 755 /usr/local/bin/$batch_measurement && echo "[OK]"
if [ $? -ne 0 ]; then echo "[KO]"; echo "--> For further details, please consult the file log.txt" && cd "$oldPath" && exit 1; fi;


cd "${oldPath}"
echo
echo "** Installation process is over. Enjoy the WiFi positining. **"
echo "** First of all, run the $pos80211_loader script for loading the pos8011 module and thus enabling the sample gathering (only once)**"
echo "** Then, run the $exec_filename script for reading the samples **"

# Deleting log
rm -f log.txt &> /dev/null


