#!/bin/bash
#auth: ZhangHao

check(){
  clear
  echo -e "\e[5;34m检测 部署 环境中...\e[0m"
  hostname | grep '\.'
  [ $? != 0 ] && echo  -e "\e[31m [ERROR \e[0m] The host name does not conform to the standard. Please change the host name and show it, such as (xxx.com) (主机名不符合规范,请改主机名并重试 如 xxx.com )" && exit
  if [ $UID != 0 ];then
     echo -e "\e[31m ERROR \e[0m] Please use root to execute the installation script (请
用 root 用户执行安装脚本)\e[0m"  && exit 1
  fi
}

install_sendmail(){
  if command -v yum;then
    yum -y install mailx  nss-tools sendmail
    [ $? != 0 ] && echo  -e "\e[31m [ERROR \e[0m] 下载软件包失败,请源并重试 (Failed to download the package, please source and try again.)" && exit
  else
    apt-get update && apt-get install  -y  libnss3-tools mailutils sendmail 
    [ $? != 0 ] && echo  -e "\e[31m [ERROR \e[0m] 下载软件包失败,请源并重试 (Failed to download the package, please source and try again.)" && exit
  fi 
}

get_crt(){
  mkdir ~/.certs/
  read -p "请输入邮件服务器 如(smtp.qq.com:465): " MAILSERVER
  smtp=`echo ${MAILSERVER} | cut -d. -f2`
  echo -n | openssl s_client -connect ${MAILSERVER} | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/${smtp}.crt
  certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/${smtp}.crt
  certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/${smtp}.crt
  certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ~/.certs -i ~/.certs/${smtp}.crt
  certutil -L -d ~/.cert
}

modify_config(){
  read -p "请输入发送邮件地址 如(xxx.qq.com): " MAIL
  read -p "请输入授权码(注!!不是qq密码,不知道的自行百度): " AUTH

  cat > /etc/mail.rc <<EOF
  set from=${MAIL}
  set smtp=smtps://${MAILSERVER} 
  set smtp-auth-user=$MAIL
  set smtp-auth-password=${AUTH}
  set smtp-auth=login
  set set nss-config-dir=~/.certs/
EOF
}

start_sendmail(){
  command -v systemctl && systemctl start sendmail && UP="systemctl start sendmail"
  command -v service && service sendmail start  && UP="service sendmail start"
  echo $UP
}

print_info(){
  echo -e "\e[33m
 _____  _   _ 
|__  / | | | |
  / /  | |_| |
 / /_  |  _  |
/____| |_| |_|
博客地址: http://www.zhanghaobk.com 云盘地址: http://www.haoyun66.cloud
QQ群: 706080502 
部署完成...

端口:25
启动sendmail命令: ${UP}
证书路径:~/.certs
配置文件路径:/etc/mail.rc

运行一下命令测试是否成功
########################################################
echo "hello world" | mail -s "test" ${MAIL}
########################################################

  \e[0m"
}

main(){
  check 
  install_sendmail
  get_crt
  modify_config
  start_sendmail
  print_info
}

main