#!/bin/bash

workdir=/data
function errexit() {
        echo "error,请在github上提出问题以待解决，谢谢"
        exit 1
}

GOVERSION=1.23.3

which systemctl  > /dev/null
if [[ $? -ne 0 ]];then
        echo "OS not support this script"
        exit 1
fi

mkdir -p /data
cd /data
# 管理包
packmanager=apt

which yum > /dev/null
if [[ $? -eq 0 ]];then
        packmanager=yum
fi
which git  > /dev/null
if [[ $? -ne 0 ]];then
        sudo $packmanager install -y git
fi

which wget > /dev/null
if [[ $? -ne 0 ]]; then
        sudo $packmanager -y install wget
fi

which tar > /dev/null
if [[ $? -ne 0 ]]; then
        sudo $packmanager -y install tar
fi

which go  > /dev/null
if [[ $? -ne 0 ]];then
        wget https://golang.google.cn/dl/go${GOVERSION}.linux-amd64.tar.gz
        tar -xf go${GOVERSION}.linux-amd64.tar.gz
        ln -s /data/go/bin/* /usr/bin/
fi


# look country
country=$(curl -s https://ipinfo.io | grep "country" | awk -F'"' '{print $4}')
if [[ $country -eq "CN" ]]; then
        git clone https://gitee.com/cander/scs.git
        go env -w GOPROXY=https://goproxy.cn
else
        git clone https://github.com/hyahm/scs.git
fi
#
cd scs
if [[ ! -f /data/scs/scsd ]];then
        go build -o scsd cmd/scsd/scsd.go
fi
which scsctl > /dev/null
if [[ $? -ne 0 ]]; then
        go build -o /usr/local/bin/scsctl cmd/scsctl/scsctl.go
fi
TOKEN=$(go run cmd/random/random.go)
if [[ ! -f /etc/scs.yaml ]];then
sudo /bin/bash -c "export TOKEN='$TOKEN' && cat > /etc/scs.yaml << EOF
# 监听端口
listen: :11111
# 服务日志配置
log:
    path: log
    day: true
    size: 0
# 请求头认证 Token： xxxx
token: '$TOKEN'
# 本地磁盘， cpu， 内存监控项， 确保elert存在才会有通知
probe:
  # mem使用率, 默认90
  mem: 60
  # cpu使用率, 默认90
  cpu: 90
  # 硬盘使用率， 默认85
  disk: 80
  # 排除的挂载点， 默认已经去掉了swap， 设备, 数组
  excludeDisk:
  # 检测间隔， 默认10秒
  interval: 10s
  # 下次报警时间间隔， 如果恢复了就重置
  continuityInterval: 1h
scripts:
  # - name: ls
  #   # 脚本执行的根目录
  #   dir: D:\\myproject\\scs
  #   env:
  #     GOPROXY: MMMM
  #   # 启动脚本
  #   command: 'go'
  #   # 不写默认10分钟
  #   continuityInterval: 1h
  #   always: true
  #   # 禁用报警， 默认启动
  #   # disableAlert: true
  #   # replicate， 开启副本数
  #   replicate: 1
  #   killTime: 2s
  #   alert:
  #     email:
  #       - 727023885460@qq.com
  #
  #     rocket:
  #       - ''
EOF"
cat > ~/.scsctl.yaml <<EOF
nodes:
  localhost:
    url: https://127.0.0.1:11111
    token: '$TOKEN'
EOF
fi

sudo /bin/bash -c "cat > /etc/systemd/system/scsd.service <<EOF
[Unit]
Description=Scs Service Control Script
After=network.target
After=network-online.target
Wants=network-online.target
[Service]
LimitNOFILE=6553500
LimitNPROC=6553500
WorkingDirectory=$workdir/scs
ExecStart=$workdir/scs/scsd -f /etc/scs.yaml
ExecStop=/bin/kill -s QUIT \$MAINPID
Type=simple
[Install]
WantedBy=multi-user.target
EOF"
sudo setenforce 0
systemctl daemon-reload
sudo systemctl start scsd
sudo systemctl enable scsd