#!/usr/bin/env bash

set -eu
trap 'echo -e "\nError occurred on line $LINENO:\n$BASH_COMMAND"; exit 1' ERR

cd $(dirname $0)

export CONFIG_FILE="/data/global.yaml"
export LOCK_FILE="/data/.initlock"


function renderTpl(){
  [ $# = 0 ] && echo "模板参数不能为空" && exit 1
  [ ! -f $1 ] && echo "$1 模板文件不存在" && exit 1
  str="$(cat $1)"
  while [[ "$str" =~ (\{\{[ ]*(\$[a-zA-Z_][a-zA-Z_0-9]*)[ ]*\}\}) ]]; do
    tpl=${BASH_REMATCH[1]}
    name=${BASH_REMATCH[2]}
    val="$(eval echo $name)"
    if [ "$val" = "" ]; then
     echo "$name 变量不存在或值为空 line:$line"
     exit 1
    fi
    str=${str//$tpl/$val}
  done; echo "$str" > $2
}


prepairServices() {
  echo "重置全局配置和服务配置"

  echo '当前版本'
  cat ./version.sh

  source ./version.sh
  renderTpl ./global-tpl.yaml $CONFIG_FILE
  renderTpl ./compose-tpl.yaml /data/services/docker-compose.yaml

  bash -c 'cd /data/services; docker compose up -d;'

  local uid=$(loginctl list-sessions --no-legend |grep tty| awk '{print $2}' | head -n 1)
  local username=$(id -nu $uid)

  if [ "$username" == "root" ]; then
    mkdir -p /root/.config/systemd/user/
    cp -f /data/screen/kadaya.service /root/.config/systemd/user/kadaya.service
    systemctl --user daemon-reload
    systemctl --user enable kadaya.service
  else
    su "$username" -s /bin/bash <<EOF
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus"
mkdir -p /home/${username}/.config/systemd/user/
cp -f /data/screen/kadaya.service /home/${username}/.config/systemd/user/kadaya.service
systemctl --user daemon-reload
systemctl --user enable kadaya.service
EOF
  fi

}

prepairSystem() {
  echo "重置machine-id,hostname"

  rm -f /etc/machine-id /var/lib/dbus/machine-id || true
  systemd-machine-id-setup &> /dev/null

  local hname="ms${screenNum}"
  hostnamectl set-hostname $hname
  sed -i '/^127\.0\.0\.1/d' /etc/hosts
  sed -i '1i 127.0.0.1\tlocalhost '"${hname}" /etc/hosts
}

prepairRemoteManager() {
  echo "重置远程管理"

  sed -i "s/screen-[a-zA-Z0-9-]*/screen-$screenNum/g" /data/soft/frp/frpc.toml

  sudo rustdesk --password txry2025

  systemctl restart frpc
  systemctl restart rustdesk
}


if [ -f "$LOCK_FILE" ]; then
    echo "已经初始化过，上次初始化时间: $(cat ${LOCK_FILE})"
    read -p "是否要重新初始化? (y/n): " answer
    if [ "$answer" != "y" ] && [ "$answer" != "Y" ]; then
        exit 0
    fi
fi

## 执行初始化流程
while [[ -z "${screenNum:+x}" ]]; do
    read -p "请输入设备号: " screenNum
    if [[ -z "$screenNum" ]]; then
        echo "输入不能为空，请重新输入！"
    fi
done

prepairSystem
prepairRemoteManager
prepairServices

echo $(date "+%Y-%m-%d %H:%M:%S") > "$LOCK_FILE"

echo "done"

