#!/bin/bash

sudo apt update                               || exit 1
sudo apt upgrade -y                           || exit 1

sudo apt install python3 python3-pip python3-tk python3-pil python3-pil.imagetk -y || exit 1

python3 -m pip install --upgrade pip          || exit 1
python3 -m pip install pyserial               || exit 1
python3 -m pip install opencv-contrib-python  || exit 1
python3 -m pip install pillow                 || exit 1
python3 -m pip install pyglet                 || exit 1
python3 -m pip install noise                  || exit 1
python3 -m pip install numpy                  || exit 1

sudo apt-get install cmake gfortran \
 libjpeg-dev libtiff-dev libgif-dev \
 libavcodec-dev libavformat-dev libswscale-dev \
 libgtk2.0-dev libcanberra-gtk* \
 libxvidcore-dev libx264-dev libgtk-3-dev \
 libtbb2 libtbb-dev libdc1394-22-dev libv4l-dev \
 libopenblas-dev libatlas-base-dev libblas-dev \
 libjasper-dev liblapack-dev libhdf5-dev \
 protobuf-compiler -y

cd ~/Downloads

wget -O opencv.zip https://github.com/opencv/opencv/archive/4.5.0.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.5.0.zip

unzip opencv.zip
unzip opencv_contrib.zip

mv opencv-4.5.0 opencv
mv opencv_contrib-4.5.0 opencv_contrib

cd opencv/
mkdir build
cd build

cmake -D CMAKE_BUILD_TYPE=RELEASE \
      -D CMAKE_INSTALL_PREFIX=/usr/local \
      -D OPENCV_EXTRA_MODULES_PATH=~/Downloads/opencv_contrib/modules \
      -D ENABLE_NEON=ON \
      -D ENABLE_VFPV3=ON \
      -D WITH_OPENMP=ON \
      -D BUILD_TIFF=ON \
      -D WITH_FFMPEG=ON \
      -D WITH_TBB=ON \
      -D BUILD_TBB=ON \
      -D BUILD_TESTS=OFF \
      -D WITH_EIGEN=OFF \
      -D WITH_V4L=ON \
      -D WITH_LIBV4L=ON \
      -D WITH_VTK=OFF \
      -D WITH_QT=OFF \
      -D OPENCV_ENABLE_NONFREE=ON \
      -D INSTALL_C_EXAMPLES=OFF \
      -D INSTALL_PYTHON_EXAMPLES=OFF \
      -D BUILD_NEW_PYTHON_SUPPORT=ON \
      -D BUILD_opencv_python3=TRUE \
      -D OPENCV_GENERATE_PKGCONFIG=ON \
      -D BUILD_EXAMPLES=OFF ..

# enlarge swapfile for building on raspi

sudo cp /etc/dphys-swapfile /etc/dphys-swapfile.bak
echo "CONF_SWAPFILE=2048" | sudo tee /etc/dphys-swapfile

sudo systemctl stop dphys-swapfile
sudo systemctl start dphys-swapfile

# build opencv

make -j4
sudo make install

sudo ldconfig
make clean
sudo apt-get update

cd ~/Downloads
rm opencv.zip
rm opencv_contrib.zip

# restore swapfile

sudo cp /etc/dphys-swapfile.bak /etc/dphys-swapfile

echo "reboot to finish!"
