#!/bin/bash
#FileName: git_install.sh
#Description: Script for git
#Author: shuhui

# Define Variables
GLOBAL_NAME="admin"
GLOBAL_EMAIL="admin@vqiu.cn"

# Define Repositories Directory
GIT_DIR="/git"

# Define IP Address
IP="127.0.0.1"

function git_install {

	# Install git 
	git > /dev/null 2>&1
	if [[ ${$?} -eq 0 ]]; then
		echo "git is already installed"
	else
		yum -y install git
	fi

	# Set Global Info.
	git config --global user.name ${GLOBAL_NAME}   
	git config --global user.email ${GLOBAL_EMAIL}

	# Generate the Keys
	if [[ ! -e ~/.ssh/id_rsa ]]; then
		ssh-keygen -t rsa -b 2048 -P "" -f ~/.ssh/id_rsa -C ${GLOBAL_EMAIL}
	fi
}

function add_user {
    id git >/dev/null 2>&1
    if [[ $? -eq 1 ]]; then
        useradd -s /usr/bin/git-shell -c "git user" git
    fi 
}

function create_repos {
	if [[ ! -d /git ]]; then
		mkdir -p ${GIT_DIR}
	fi
	cd ${GIT_DIR}
	git init --bare sample.git
	
	# Setup Repositories Privileges
	chown -R git.git ${GIT_DIR}
}

function import_pkey {
	if [[ ! -d /home/git/.ssh ]]; then
		mkdir /home/git/.ssh
		chmod 700 /home/git/.ssh
		chown git.git /home/git/.ssh
	fi
	
	if [ -e /tmp/id_rsa.pub ]; then
		\rm -rf /tmp/id_rsa.pub
	fi
	
	cp /root/.ssh/id_rsa.pub /tmp
	cat /tmp/id_rsa.pub > /home/git/.ssh/authorized_keys
	chown git.git /home/git/.ssh/authorized_keys
	chmod 600 /home/git/.ssh/authorized_keys
}

function client {
	
	cd ~
	# Clone the Gitosis-admin Repositories
	git clone git@${IP}:${GIT_DIR}/sample.git
}

git_install
add_user
import_pkey
create_repos
client
