#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

CONFIG=/etc/zzz/config.ini

start_service() {
  # 检查是否启用
  local enabled=$(uci -q get zzz.general.enabled)
  [ "$enabled" = "1" ] || {
    echo "zzz is disabled"
    return 1
  }

  generate_config

  procd_open_instance
  procd_set_param command /usr/bin/zzz "$CONFIG"
  procd_set_param respawn
  procd_close_instance
}

stop_service() {
  procd_kill zzz
}

generate_config() {
  mkdir -p /etc/zzz

  # 获取UCI配置
  local username=$(uci -q get zzz.auth.username)
  local password=$(uci -q get zzz.auth.password)
  local device=$(uci -q get zzz.auth.device)

  # 检查必要参数
  [ -z "$username" ] && {
    logger -t zzz "Error: username not configured"
    return 1
  }

  [ -z "$password" ] && {
    logger -t zzz "Error: password not configured"
    return 1
  }

  # 生成INI配置文件
  cat >"$CONFIG" <<EOF
[auth]
username = $username
password = $password
device = ${device:-eth0}
EOF
}
