#!/bin/bash
Mode=prod
error_flag=0

function version {
echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }';
}

function install_ {
echo -e "$(tput setaf 10)\nInstall / Update cmake :$(tput sgr0)"
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.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 version : $cmake_v"
        sleep 2
        if ! [ $(version $cmake_v) -ge $(version "3.18") ]
        then
        echo -e "cmake need 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 ok."
        sleep 2
        fi
        ;;
*)      echo "Error";;
esac
echo "Done"
}

function rollback {
echo -e "$(tput setaf 10)\nInstall / Update cmake :$(tput sgr0)"
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 "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




