#!/bin/bash
# FileName: Change_Mirrors.sh
# Description: Modify System Mirrors, Just for CentOS Branch 
# Author: Shuhui

######################## Define Variables Start ########################
CENTOS_REPO_DIR='/etc/yum.repos.d'
REPO_6='http://mirrors.163.com/.help/CentOS6-Base-163.repo'
REPO_7='http://mirrors.163.com/.help/CentOS7-Base-163.repo'
######################## Define Variables End ########################

function Install_Check_Tool()
{
	if [[ -e /usr/bin/yum ]]
	then 
		echo "Your System is CentOS(RHEL)"
		if [[ ! -e /usr/bin/lsb_release ]]
		then
			yum -y install redhat-lsb-core >/dev/null
		fi
	fi
}

function CentOS_6()
{
	if [[ ! -e ${CENTOS_REPO_DIR}/${REPO_6##*/} ]]
	then
		# Create Backup Directory
		if [[ ! -d ${CENTOS_REPO_DIR}/save ]]
		then
			mkdir -p ${CENTOS_REPO_DIR}/save
		fi
		
		# Move File to Backup Dir
		\mv ${CENTOS_REPO_DIR}/*.repo ${CENTOS_REPO_DIR}/save
		
		# Download Repo File
		curl ${REPO_6} > ${CENTOS_REPO_DIR}/${REPO_6##*/}
		if [[ $? -eq "0" ]]
		then
			yum clean all && yum makecache
		else
			echo "Sorry,Failed."
			\mv ${CENTOS_REPO_DIR}/save/*.repo ${CENTOS_REPO_DIR}/
		fi
	else
		echo "Skip";exit -1;
	fi
}

function CentOS_7()
{
	if [[ ! -e ${CENTOS_REPO_DIR}/${REPO_7##*/} ]]
	then
		# Create Backup Directory
		if [[ ! -d ${CENTOS_REPO_DIR}/save ]]
		then
			mkdir -p ${CENTOS_REPO_DIR}/save
		fi
		
		# Move File to Backup Dir
		\mv ${CENTOS_REPO_DIR}/*.repo ${CENTOS_REPO_DIR}/save
		
		# Download Repo File
		curl ${REPO_7} > ${CENTOS_REPO_DIR}/${REPO_7##*/}
		if [[ $? -eq "0" ]]
		then
			yum clean all && yum makecache
		else
			echo "Sorry,Failed."
			\mv ${CENTOS_REPO_DIR}/save/*.repo ${CENTOS_REPO_DIR}/
		fi
	else
		echo "Skip";exit -1;
	fi
}

Install_Check_Tool

if [[ $(lsb_release -i|awk '{print $3}') -eq 'CentOS' ]] && [[ $(lsb_release -r|awk  '{print $2}'|awk -F '.' '{print $1}') -eq '7' ]]
then 
	CentOS_7
elif [[ $(lsb_release -i|awk '{print $3}') -eq 'CentOS' ]] && [[ $(lsb_release -r|awk  '{print $2}'|awk -F '.' '{print $1}') -eq '6' ]]
then
	CentOS_6
fi
