#!/bin/bash

GIT_VERSION=2.33.0
URL="https://mirrors.edge.kernel.org/pub/software/scm/git/git-$GIT_VERSION.tar.gz"
#URL="https://github.com/git/git/archive/refs/tags/v$GIT_VERSION.tar.gz"
INSTALL_DIR=/apps/git

CPUS=`lscpu |awk '/^CPU\(s\)/{print $2}'`
#CPUS=`grep -c processor /proc/cpuinfo`

. /etc/os-release

color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}

prepare(){
    if [ $ID = "centos" -o $ID = "rocky" ];then
        yum  -y install gcc make  openssl-devel curl-devel expat-devel wget
    else
        apt update
        apt -y install gcc make libcurl-openssl1.0-dev libexpat1-dev gettext wget
    fi
    if [ $? -eq 0 ];then
        color "安装软件包成功"  0
    else
        color "安装软件包失败,请检查网络配置" 1
        exit
    fi
}

install () {
    if [ ! -f v$GIT_VERSION.tar.gz ];then
        wget  -P /usr/local/src $URL || { color "git 源码下载失败" 1 ; exit; }
    fi
   	tar xf /usr/local/src/*$GIT_VERSION.tar.gz -C /usr/local/src
    cd /usr/local/src/git-$GIT_VERSION
    make -j $CPUS all && \
    make install prefix=$INSTALL_DIR
    if [ $? -eq 0 ];then 
        color "Git 编译安装完成" 0 
    else
        color "Git 编译安装失败" 1
        exit
    fi
    echo PATH="$INSTALL_DIR/bin/":'$PATH' > /etc/profile.d/git.sh
    . /etc/profile.d/git.sh
    ln -s $INSTALL_DIR/bin/* /usr/local/bin
    git version
}

prepare 
install