#!/usr/bin/env bash

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

cd $(dirname $0)
source ./lib.sh
source ./version.sh
export LOCK_FILE="/apps/.data/.initlock"

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

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

  local hname="ds${deviceNo}"
  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/device-[a-zA-Z0-9-]*/device-$deviceNo/g" /apps/frpc/frpc.toml

  sudo rustdesk --password snap2025

  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 "${deviceNo:+x}" ]]; do
    read -p "请输入设备号: " deviceNo
    if [[ -z "$deviceNo" ]]; then
        echo "输入不能为空，请重新输入！"
    fi
done

echo 程序版本
cat ./version.sh
echo ''

prepairSystem
syncGlobalConfig
setupFlutterService
# 先固定手动
export printType=1
setupDockerServices
prepairRemoteManager

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

echo "done"

