#!/usr/bin/env bash
# 文件名: registry_deploy.sh
# 作者: 树辉<shuhui@vqiu.cn>
# vim:sw=4:ts=4:et

set -e

# 终端颜色定义
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}

TEMP_PATH=$(mktemp -d)
DATA_DIR=/data/docker-registry
PORT=${1:-5000}
BIN_FILE=/usr/sbin/registry
SERVICE_NAME=docker-distribution
CONF_FILE=/etc/docker-distribution/config.yml
VERSION=3.0.0

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

if [[ "$(systemctl is-enabled ${SERVICE_NAME})" != "enabled" ]]
then

    sed -n -e '1,/^exit 0$/!p' $0 > ${TEMP_PATH}/registry-${VERSION}.tar.gz 2>/dev/null

    install -d ${DATA_DIR} ${CONF_FILE%/*}

    tar axvf ${TEMP_PATH}/registry-${VERSION}.tar.gz -C ${TEMP_PATH} >/dev/null
    sleep 2 >/dev/null
    cp -rf ${TEMP_PATH}/registry-${ARCH} ${BIN_FILE} >/dev/null 2>/dev/null
    chmod +x ${BIN_FILE} >/dev/null 2>/dev/null

    cat > ${CONF_FILE} <<EOF
version: 0.1
log:
  fields:
    service: registry
storage:
  cache:
    blobdescriptor: inmemory
  filesystem:
    rootdirectory: ${DATA_DIR}
  #delete:
  #  enabled: true
http:
  addr: :${PORT}
  headers:
    X-Content-Type-Options: [nosniff]
  #tls:
  #  certificate: /etc/docker-distribution/crt.pem
  #  key: /etc/docker-distribution/key.pem
#auth:
#  htpasswd:
#    realm: basic-realm
#    path: /etc/docker-distribution/.auth
health:
  storagedriver:
    enabled: true
    interval: 10s
    threshold: 3
EOF

cat > /etc/systemd/system/${SERVICE_NAME}.service<<EOF
[Unit]
Description= v3 Registry server for Docker

[Service]
Type=simple
ExecStart=/usr/sbin/registry serve ${CONF_FILE}
Restart=on-failure

[Install]
WantedBy=multi-user.target
Alias=docker-registry.service
EOF
    systemctl daemon-reload
    systemctl restart  ${SERVICE_NAME}.service
    systemctl enable ${SERVICE_NAME}.service
else
    printf "$warn: ${SERVICE_NAME} 服务已安装,正常退出!\n" && exit 67
fi

rm -rf ${TEMP_PATH}
exit 0
