#!/bin/sh

# copy config files
for i in etc lib usr
do
  sudo cp -r $i/* /$i/
done
cp -r home/pi/.* /home/pi/

# network
echo "Networking installed, use WiFi for Internet"

# update & clean
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install -y ntpdate subversion git cmake
sudo apt-get -y autoremove
sudo apt-get clean

# Need rc.local to start CAN and BSMPd
sudo systemctl enable rc-local.service
if [ ! -f /etc/init/x11vnc.conf ]; then
  sudo systemctl enable x11vnc.service
fi

# time
sudo ntpdate pool.ntp.org
sudo hwclock -w
sudo apt-get update

# clone/pull
mkdir -p $HOME/ProbeStar
cd $HOME/ProbeStar
for i in git_tools linux_tools pi_tools Cnomicon Pynomicon
do
  if [ -d $i ]; then
    cd $i
    git config credential.helper store
    git pull --recurse-submodules
    cd ..
  else
    git clone https://github.com/nprobert/$i --recurse-submodules
  fi
done
cd $HOME
for i in ProbeStar/*; do
  ln -fs $i
done
mkdir bin
cp linux_tools/bin/* bin/

# checkouts
mkdir -p $HOME/NTCNA
cd $HOME/NTCNA
for i in CVehicle PyVehicle
do
  if [ -d $i ]; then
    cd $i
    git config credential.helper store
    git pull --recurse-submodules
    cd ..
  else
    git clone https://github.com/nprobert/$i --recurse-submodules
  fi
done
cd $HOME
for i in NTCNA/*; do
  ln -fs $i
done

# packages & builds
if [ -d $HOME/ProbeStar/Cnomicon ]; then
  cd $HOME/Cnomicon/packages
  ./packages.sh
  cd ..
  ./cbuild.sh
  ./cinstall.sh
fi

if [ -d $HOME/NTCNA/CVehicle ]; then
  cd $HOME/CVehicle/packages
  ./packages.sh
  cd ..
  ./cbuild.sh
  ./cinstall.sh
fi

# python stuff
cd $HOME/NTCNA/Pynomicon/packages
./packages.sh
chmod +x $HOME/Pynomicon/bin/*.sh
cd $HOME/NTCNA/PyVehicle/packages
./packages.sh
chmod +x $HOME/PyVehicle/bin/*.sh

# cleanup
sudo raspi-config

git config --global user.email "nprobert@probestar.net"
git config --global user.name "Neal Probert"
