#!/bin/bash
export http_port=7618
# 检查当前用户是否为 root
if [ "$EUID" -ne 0 ]; then
    echo -e "\e[91m请使用 root 用户或 sudo 权限执行安装器启动程序(startup.sh)\e[0m"
    exit 1
fi
workdir=$(dirname $(readlink -f "$0"))
# 给singularity/bin 目录赋 0755
chmod 0755 -R $workdir
# 修改gpaas初始化脚本
sed -i "s/export http_port=\S*$/export http_port=${http_port}/g" $workdir/../scripts/initialize/gpaas/init.sh
# 放行防火墙端口
firewall-cmd --zone=public --add-port="$http_port"/tcp --permanent
firewall-cmd --reload

# 检查已经占用端口是不是安装器占用的
if [ $(ss -tulnp | grep ":$http_port " | wc -l) != 0 ]; then
  # 不是安装器占的
  if [ $(ss -tulnp | grep ":$http_port " | grep "singularity" | wc -l) == 0 ]; then
    echo "端口被非安装器应用占用，具体信息如下："
    echo "$(ss -tulnp | grep ":$http_port ")"
    exit 1
  fi
fi

runtimedir=$workdir/../runtime
mkdir -p $runtimedir
chmod -R +x $workdir/../scripts/ && $workdir/../scripts/k8s/shell/install-kernel.sh && cd $runtimedir && $workdir/prestart
# 如果是安装器已经启动，go程序会打印日志
if [ $? -eq 0 ]; then
  echo '正在启动安装器...'
  cd $runtimedir && nohup $workdir/singularity >> /dev/null 2>&1 &
  sleep 10
  tail -12 $runtimedir/logs/default.log
else
  exit 2
fi
