#!/bin/sh

# ── 1. 从 factory 分区读取 MAC ──────────────────────────────
ETH_MAC=$(hexdump -s 0x28 -n 6 -e '5/1 "%02x:" 1/1 "%02x"' /dev/mtd2)

case "$ETH_MAC" in
"00:00:00:00:00:00" | "ff:ff:ff:ff:ff:ff")
  logger -t uci-defaults "Invalid MAC in factory, skipping"
  exit 1
  ;;
esac

ETH_DEV=$(uci show network | grep "\.name='eth0'" | cut -d. -f2)

if [ -n "${ETH_DEV}" ]; then
  uci set "network.${ETH_DEV}.macaddr=${ETH_MAC}"
else
  uci set network.wan_eth0_dev=device
  uci set network.wan_eth0_dev.name='eth0'
  uci set "network.wan_eth0_dev.macaddr=${ETH_MAC}"
fi

uci set network.lan.ipaddr='192.168.11.1'
uci set network.lan.netmask='255.255.255.0'
# 解决当 wlan1 出现问题的时候 br-lan 会变为失效的情况
uci delete network.@device[0].ports
uci set network.@device[0].bridge_empty='1'
# 修复网络优先级的问题
uci set network.wan.metric='10'
uci set network.wwan0.metric='20'
uci commit network
wifipasswd=$(/root/genpasswd "$ETH_MAC")
# ── 3. 取 MAC 后5位作为设备唯一标识 ─────────────────────────
# 直接从 factory 读取的 MAC 截取，不依赖 /sys/class/net/eth0/address
# 因为此时网络还未启动，/sys 里可能还是随机 MAC
mac=$(echo "$ETH_MAC" | tr -d ':' | tail -c 5)
ETH_MAC=$(echo "$ETH_MAC" | tr -d ':')

# ── 4. 无线：SSID / 密码 ─────────────────────────────────────
uci set wireless.ap0.ssid="Vida-${mac}"
uci set wireless.ap0.encryption='psk2'
uci set wireless.ap0.key="$wifipasswd"
uci commit wireless

# ── 5. 主机名 ────────────────────────────────────────────────
uci set system.@system[0].hostname="Vida-${mac}"
uci commit system

# ── 6. 防火墙：允许 WAN SSH + WAN zone 全放通 ────────────────
uci add firewall rule
uci set firewall.@rule[-1].name='Allow-SSH-from-WAN'
uci set firewall.@rule[-1].src='wan'
uci set firewall.@rule[-1].dest_port='22'
uci set firewall.@rule[-1].proto='tcp'
uci set firewall.@rule[-1].target='ACCEPT'
uci set firewall.@zone[1].input='ACCEPT'
# 添加上 wifi 热点作为上网源
uci add_list firewall.@zone[1].network='wwan0'
uci commit firewall

# frpc setup
cat >/root/frpc/frpc.ini <<EOF
[common]
server_addr = 52.76.238.26
server_port = 7000
token = 4a497e82e13b2d1c57db9710cd63764b507b8944aeb8a0457813b0afd4fcce2c
client_id = ${ETH_MAC}
log_file     = /tmp/frpc.log
log_max_size = 1          
log_max_num  = 1

[ssh-test]
type = tcp
local_ip = 127.0.0.1
local_port = 22
EOF

# ── 7. 启用自定义服务 ────────────────────────────────────────
if [ ! -f "/root/without_zwave" ]; then
  /etc/init.d/zwave enable
fi
/etc/init.d/zigbee enable
/etc/init.d/ha_web_ui enable
# /etc/init.d/mqtt_cmd enable
/etc/init.d/ha_register enable
/etc/init.d/check_network enable
/etc/init.d/frpc enable
/etc/init.d/cron enable
/etc/init.d/rpcd disable
/etc/init.d/travelmate disable

logger -t uci-defaults "Init done, MAC=$ETH_MAC, ID=Vida-${mac}"

# wg 的相关设置
mkdir -p /etc/config/wireguard/
if [ ! -f "/etc/config/wireguard/private.key" ]; then
  echo "gen wg private/public key"
  wg genkey >/etc/config/wireguard/private.key
  cat /etc/config/wireguard/private.key | wg pubkey >/etc/config/wireguard/public.key
fi

exit 0
