#!/bin/bash
Mode=prod
error_flag=0
export TERM=xterm-256color

function version {
echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }';
}
function intro_ {
echo -e "$(tput setaf 10)Install / Update cmake tool v2.0 :$(tput sgr0)"
}

function install_ {
intro_
if [ -x "$(command -v cmake)" ];then flag=1; else flag=0;fi
case $flag in
0)
	echo "cmake not installed..."
        wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/cmake_3.26.4-1_amd64.deb
        sudo dpkg -i cmake_3.26.4-1_amd64.deb
        rm cmake_3.26.4-1_amd64.deb
        ;;
1)
        cmake_v="$(cmake --version | grep "version" | awk '{print $3}')"
        echo "cmake installed version : $(tput setaf 11)$cmake_v$(tput sgr0)"
        sleep 2
        if ! [ $(version $cmake_v) -ge $(version "3.18") ]
        then
        echo -e "cmake need to update=> cmake_3.26.4"
        sudo apt-get -qq remove --purge cmake -y
        wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/cmake_3.26.4-1_amd64.deb
        sudo dpkg -i cmake_3.26.4-1_amd64.deb
        rm cmake_3.26.4-1_amd64.deb
        else
        echo -e "cmake version : $(tput setaf 13)OK$(tput sgr0)"
        sleep 2
        fi
        ;;
*)      echo "Error";;
esac
echo -e "Done."
}

function rollback {
intro_
if [ -x "$(command -v cmake)" ];then flag=1; else flag=0;fi
case $flag in
0)
        wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/cmake_3.16.3-1_amd64.deb
        sudo dpkg -i cmake_3.16.3-1_amd64.deb
        rm cmake_3.16.3-1_amd64.deb
        ;;
1)
        cmake_v="$(cmake --version | grep "version" | awk '{print $3}')"
        echo "cmake version : $cmake_v"
        sleep 2
        if [ $(version $cmake_v) -gt $(version "3.18") ]
        then
        echo -e "cmake need rollback to cmake_3.16.3"
        sudo apt-get -qq remove --purge cmake -y
        wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/cmake_3.16.3-1_amd64.deb
        sudo dpkg -i cmake_3.16.3-1_amd64.deb
        rm cmake_3.16.3-1_amd64.deb
        else
        echo -e "cmake version OK."
        sleep 2
        fi
        ;;
*)      echo "Error";;
esac
echo -e "Done."
}


function cmake_source {
echo -e "$(tput setaf 12)Cmake kitware build:$(tput sgr0)"
sleep 2
sudo apt-get install checkinstall -y
wget -c https://github.com/Kitware/CMake/releases/download/v3.26.4/cmake-3.26.4.tar.gz
tar xvfz cmake-3.26.4.tar.gz
cd cmake-3.26.4
./bootstrap
make -j6
sudo checkinstall --pkgname=cmake --pkgversion="3.26.4" --default
hash -r
}

Mode=${Mode^^}
if [ -z $1 ];then install_ && exit;fi
if [ $1 = "rollback" ];then rollback;fi
if [ $1 = "BUILD" ];then cmake_source;fi




