#!/usr/bin/env bash
# 文件名: haproxy_tarball_install.sh
# 描述: haproxy 编译脚本
# 作者: shuhui@2017
# 备注: 依赖 gcc

### 定义变量 开始

export tag=wd
export build_dir=/usr/local/src
export src_dir=/opt/${tag}/src
export cnf_dir=/opt/${tag}/etc/haproxy
export app_dir=/opt/${tag}/app
export run_dir=/opt/${tag}/run/haproxy
export log_dir=/data/logs/haproxy


export owner=haproxy
export uid=188
export gid=188

haproxy_ver=1.7.5
haproxy_url="http://pro.vqiu.cn/haproxy-${haproxy_ver}.tar.gz"

### 定义变量 结束

# 判断当前用户是否为 root,否则退出
if [ ${UID} != "0" ]; then
	echo "Error: Please use root role to install me!"
	exit 67
fi

yum -y install gcc

# 创建 $owner
id ${owner} >/dev/null 2>&1
if [ $? -eq "1" ];
then
	groupadd ${owner} -g ${gid}
	useradd -g ${gid} -u ${uid} ${owner} -s /sbin/nologin -M
fi

for dir in ${src_dir} ${cnf_dir} ${app_dir} ${run_dir} ${log_dir}
do
	mkdir -p ${dir} 
	chown -R ${owner}.${owner} ${dir}
done

cd ${build_dir}
[[ -f ${build_dir}/haproxy-${haproxy_ver}.tar.gz ]] || echo "hropxy Downloading..." && curl -sSfL ${haproxy_url} -O


tar axvf haproxy-${haproxy_ver}.tar.gz
cd haproxy-${haproxy_ver}
make -j $(nproc) TARGET=linux310 ARCH=$(uname -m) PREFIX=${src_dir}/haproxy-${haproxy_ver}
make install PREFIX=${src_dir}/haproxy-${haproxy_ver}

cd ${app_dir} && ln -svf ../src/haproxy-${haproxy_ver} ./haproxy

cat >/etc/profile.d/haproxy.sh<<EOF
export PATH=\$PATH:${app_dir}/haproxy/sbin
EOF
