#!/usr/bin/env bash

set -e

TEMP_PATH=$(mktemp -d)
NAME=containerd
VERSION="1.6.38"
#IMG_HUB=${1:-registry.aliyuncs.com/google_containers}
IMG_HUB=${1:-hub.gitee.local/base-platform}
DATA_ROOT=${2:-/data/containerd}

txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) # red
bldgre=${txtbld}$(tput setaf 2) # green
bldylw=${txtbld}$(tput setaf 3) # yellow
txtrst=$(tput sgr0)             # Reset
err=${bldred}ERROR${txtrst}
info=${bldgre}INFO${txtrst}
warn=${bldylw}WARNING${txtrst}

# 判断环境平台
if [ -z "${ARCH}" ]; then
  case $(uname -m) in
    x86_64) ARCH=amd64 ;;
    aarch64) ARCH=arm64 ;;
    *) printf "$err: 不支持该平台 $(uname -m)"; exit 1 ;;
  esac
fi

if [[ "$@" < "1" ]]; then
    echo """
用法: $(basename $0) [选项]
选项:
  --hub             [选填] 镜像地址,默认: registry.aliyuncs.com/google_containers
  --datadir         [选填] 数据目录,默认: /data/containerd
  --auth            [选填] 仓库是否带认证, true为是启用,false则不启用
  --username        [选填] 容器仓库用户
  --password        [选填] 容器仓库密码
  --pause           [选填] Pause版本,默认:3.9

使用案例

示例1. 在线部署code、scan、pipe、doc、proxima、insight 产品,附带demo初始化、自动化测试,且访问域名为 demo.gitee.work
# ./$(basename $0) --demo true --api_autotest true --namespace gitee --domain demo.gitee.work --deploy code,scan,pipe,doc,proxima,insight

示例2. 离线(私有镜像仓库地址为1.1.1.1)部署code、scan、pipe、doc、proxima、insight 产品,附带demo初始化,且访问域名为 demo.gitee.work
# ./$(basename $0) --demo true --namespace gitee --registry_server 1.1.1.1 --domain demo.gitee.work --deploy code,scan,pipe,doc,proxima,insight

示例3. 在线部署code、Proxima产品,不附带demo初始化, 且访问域名为 demo.gitee.work
# ./$(basename $0) --demo false --domain demo.gitee.work --deploy code,proxima

示例4. 在线部署lite版本, 且访问域名为 demo.gitee.work, 默认部署 proxima,code,doc,pipe
# ./$(basename $0) --lite true --domain demo.gitee.work

示例5. 在线部署lite版本, 访问域名为demo.gitee.work,且产品调整为 code,proxima
# ./$(basename $0) --lite true --domain demo.gitee.work --deploy code,proxima
"""
    exit 67
fi

# 读取命令行参数
ARGUMENT_LIST=(
    "namespace"
    "deploy"
    "lite"
    "domain"
    "webide_domain"
    "license_server"
    "registry_server"
    "demo"
    "api_autotest"
)

# 读取参数
opts=$(getopt \
    --longoptions "$(printf "%s:," "${ARGUMENT_LIST[@]}")" \
    --name "$(basename "$0")" \
    --options "" \
    -- "$@"
)

eval set --$opts

while true; do
    case "$1" in
    --namespace)  
        shift
        namespace=$1
        ;;
    --deploy)  
        shift
        deploy_products_enter_raw=$1
        deploy_products_enter=$(echo $1 | tr -s ',' ' ')
        ;;
    --lite)  
        shift
        lite="true"
        ;;
    --domain)  
        shift
        app_domain=$1
        ;;
    --webide_domain)
        shift
        webide_domain=$1
        ;;
    --license_server)
        shift
        license_server=$1
        ;;
    --registry_server)
        shift
        registry_server=$1
        ;;
    --demo)
        shift
        demo_init="true"
        ;;
    --api_autotest)
        shift
        api_autotest="true"
        ;;
      --)
        shift
        break
        ;;
    esac
    shift
done

if [[ -z $license_server ]]; then
    license_server=$(hostname -i)
fi

if [[ -z $namespace ]]; then
    namespace=gitee
fi

# 判断服务是否正常运行
if [[ "$(systemctl is-enabled ${NAME}.service)" != "enabled" ]]
then
    sed -n -e '1,/^exit 0$/!p' $0 > ${TEMP_PATH}/${NAME}-${VERSION}.tar.gz 2>/dev/null

    printf "$info: [ ${bldgre}${NAME}-${VERSION}${txtrst} ] 安装中...\n"

    cd ${TEMP_PATH}
    tar axvf ${NAME}-${VERSION}.tar.gz >/dev/null
    sleep 2 >/dev/null 2>/dev/null
    tar axvf ${NAME}-${VERSION}-${ARCH}.tar.gz -C /usr/local >/dev/null

    cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF
    modprobe overlay >/dev/null 2>/dev/null
    modprobe br_netfilter >/dev/null 2>/dev/null

    cat >/etc/systemd/system/containerd.service<<EOF
[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target

[Service]
ExecStartPre=-/sbin/modprobe overlay bridge br_netfilter 
ExecStart=/usr/local/bin/containerd
Restart=always
RestartSec=5
Delegate=yes
KillMode=process
OOMScoreAdjust=-999
LimitNOFILE=1048576
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity

[Install]
WantedBy=multi-user.target

EOF
    cat >/etc/sysctl.d/99-containerd.conf <<EOF
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward = 1
EOF
    sysctl --system >/dev/null 2>/dev/null

    mkdir -p /etc/containerd
    /usr/local/bin/containerd config default | sed -e "s@sandbox_image = .*@sandbox_image = \"${IMG_HUB}/pause:3.9\"@" \
                                                   -e "s@config_path =.*@config_path = \"/etc/containerd/certs.d\"@" \
                                                   -e "s@SystemdCgroup = .*@SystemdCgroup = true@" \
                                                   -e "s@^root = .*@root = \"${DATA_ROOT}\"@" > /etc/containerd/config.toml

    mkdir -p /etc/containerd/certs.d/${IMG_HUB##%/}
    cat > /etc/crictl.yaml <<EOF
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
EOF
    systemctl daemon-reload >/dev/null 2>/dev/null
    systemctl enable ${NAME}.service --now >/dev/null 2>/dev/null
else
    printf "$warn: [ ${bldgre}${NAME}-${VERSION}${txtrst} ] 已安装，正常退出~\n"
fi

rm -rf ${TEMP_PATH}
exit 0
