#!/bin/bash

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

# make sure that top directory is called properly

topdir=`basename $PWD`
if [ "$topdir" != "fmcmasterfip" ]
then
    echo "Projects top directory must be called \"fmcmasterfip\""
    echo "Do you want to rename it right now [y/n]"
    read res

    if [ "$res" != "y" ] || [ -z "$res" ]
    then
        echo "Abording"
        exit

    else
        cd ..
        mv "$topdir" fmcmasterfip
        cd fmcmasterfip
    fi
fi

apt-get install python-numpy python-scipy python-matplotlib ipython python2-pyro4 python-psutil python-dnspython
apt-get install git gitk libusb-dev terminator

# initialise and update repository
git submodule init
git submodule update

# build software
cd software
make
cd ..
sleep 1
# load drivers in order to check if no errors occure
./scripts/drivers_load.sh    

sleep 1

# test software
if [ `lsmod | grep fmc_adc_100m14b | wc -l` -eq 0 ]; 
then 
    
    echo "ERROR! Required drivers are not loaded correctly:"; 

    lsmod

    exit

fi

if [ `lspci | grep CERN | wc -l` -ne 1 ]
then 

    echo "ERROR! SPEC device not found" 

    lspci
else
    spec=1
fi

if [ `ls /sys/bus/zio/devices | wc -l` -ne 2 ]; 
then 
    echo "ERROR! No divice is visible in /sys/bus/zio/devices"

    if [ ! -z $spec ]
    then

        echo "ERROR! Drives might not build correctly";
        echo "Make sure that patch was correctly applied to fmc_adc_100m14b driver" 

    else
        echo "Make sure that SPEC device is mount correctly and run this script again."
    
    fi
    
    exit
    
fi


echo "Installation successful!"
echo "Creating desktop shortcut"

echo -e "[Desktop Entry]
Type=Application
Terminal=false
Name=PTSmasterFIP
Exec=terminator --working-directory=${PWD}/pts/ -e \"sudo -u root ${PWD}/pts/fmcmasterfip.sh ; bash\"
Icon=${PWD}/doc/icon.png
Comment=
Path=
StartupNotify=false
" > ~/Desktop/test_fmcmasterfip.desktop

# copy read_samples.py to logdir
LOGDIR="${HOME}/Desktop/pts_log/fmcmasterfip"
mkdir -p "$LOGDIR/adcdata"
cp "python/read_samples.py" "$LOGDIR/adcdata"

# create desktop shortcut
chmod +x ~/Desktop/test_fmcmasterfip.desktop