#!/usr/bin/env bash

export RSYNC_REMOTE="device@rsync.internal.magicsnap.cn::device"
export CONFIG_FILE="/apps/.data/.global.yaml"
export MIRROR_HOST="mirrors.huaweicloud.com"

export SCRIPT_DIR=$(dirname $(realpath "$0"))

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

declare -A COMMAND_PKG_MAP=(
  ["curl"]="curl"
  ["jq"]="jq"
  ["wget"]="wget"
  ["nc"]="netcat"
  ["rsync"]="rsync"
)

install_command_if_needed() {
  local cmd=$1
  command -v "$cmd" &>/dev/null && { return 0; }

  local pkg="${COMMAND_PKG_MAP[$cmd]}"
  [[ -z "$pkg" ]] && { echo "未找到 '$cmd' 对应的安装包"; exit 1; }

  if ! apt-cache policy "$pkg" | grep -q -E 'Candidate:|候选' ; then
    apt update -qq  >/dev/null 2>&1
  fi
  echo "安装 '$cmd' (包: $pkg)"
  apt install -y -qq "$pkg" >/dev/null 2>&1
}

install_pkg_if_needed() {
  local pkg=$1
  if ! apt-cache policy "$pkg" | grep -q -E 'Candidate:|候选' ; then
    apt update -qq >/dev/null 2>&1
  fi
  if ! dpkg -l | grep -q "$pkg"; then
    echo "安装包: $pkg"
    apt install -y -qq "$pkg" >/dev/null 2>&1
  fi
}


getDeviceNo() {
  if [[ -f "$CONFIG_FILE" ]]; then
    deviceNo=$(grep -oP '^\s*deviceNo\s*:\s*"\K[\w\-]+' "$CONFIG_FILE")
  fi

  if [[ -z "$deviceNo" ]]; then
    read -p "请输入设备号: " deviceNo
    cat > $CONFIG_FILE <<EOF
deviceNo: "$deviceNo"
EOF
  fi
  echo "$deviceNo"
}

getEnv() {
  if [ ! -f "$CONFIG_FILE" ]; then
    echo "dev"
    return 0
  fi
  echo $(grep '^env:' $CONFIG_FILE| awk '{print $2}' | tr -d '"' || echo "prod")
}

statusIcon() {
  [ $? -eq 0 ] && echo -e "\e[32m✓✓\e[0m" || echo -e "\e[31m✗✗\e[0m"
}

rrsync() {
  local sc=''
  if [ "$DEBUG" = true ]; then
    sc=' -v -P'
  fi
  rsync $sc --timeout=100 "$@"
}

getLoginUid() {
  local uid=$(loginctl list-sessions --no-legend | grep -E "tty|seat" | awk '{print $2}' | head -n 1)
  if [[ "$uid" == '' ]]; then
     uid=$(loginctl list-sessions --no-legend | awk '{print $2}' | head -n 1)
  fi
  echo $uid
}

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
}

installDocker() {
  local systemId=$(grep -oP '^ID=\K.*' /etc/os-release)
  
  ## docker
  if systemctl is-active --quiet docker; then
      echo "Docker 服务已存在"
  else
    for pkg in docker.io docker-doc docker-compose podman-docker containerd runc; do sudo apt-get remove -y $pkg; done
    
    apt-get update
    apt-get install -y ca-certificates curl gnupg
    
    install -m 0755 -d /etc/apt/keyrings
    rm -f /etc/apt/keyrings/docker.gpg
    curl -fsSL http://mirrors.huaweicloud.com/docker-ce/linux/${systemId}/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
    sudo chmod a+r /etc/apt/keyrings/docker.gpg
    echo \
    "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] http://mirrors.huaweicloud.com/docker-ce/linux/${systemId} \
    "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" |
    tee /etc/apt/sources.list.d/docker.list >/dev/null
    
    apt-get update
    apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  fi

  updateDocker
}

updateDocker() {
  echo 更新docker配置

  if [[ -f /root/.docker/config.json ]] && grep -q 'c25hcDpNYWdpYzIwMjUh' /root/.docker/config.json; then
    echo "docker已配置过了"
    return 0
  fi

  mkdir -p /etc/docker /apps/.data/docker
  cat >/etc/docker/daemon.json <<EOF
{
    "data-root": "/apps/.data/docker",
    "features": {
      "containerd-snapshotter": true  
    }
}
EOF

  mkdir -p /root/.docker
  cat >/root/.docker/config.json <<EOF
{
  "auths": {
    "harbor.internal.magicsnap.cn": {
      "auth": "c25hcDpNYWdpYzIwMjUh"
    }
  }
}
EOF

 cat >/etc/containerd/config.toml <<EOF
disabled_plugins = ["cri"]
root = "/apps/.data/containerd"
EOF

  systemctl restart containerd
  systemctl restart docker
}

function detectSystem() {
  local -n resultMap=$1
  
  tmp=$(bash <<'EOF'
echo system=$(if grep -q 'Ubuntu' /etc/os-release; then echo 'ubuntu'; elif grep -q 'Debian' /etc/os-release; then echo 'debian'; fi)
echo "hostname=$(hostname)"
EOF
  )

  while IFS='=' read -r key value; do
      resultMap["$key"]=$value
  done <<< "$tmp"
}

checkAndchangeMirrors() {
  local codename=$(grep 'VERSION_CODENAME' /etc/os-release | cut -d'=' -f2)
  local id=$(grep '^ID=' /etc/os-release| cut -d'=' -f2)

  # apt source
  local apt_content=$(cat /etc/apt/sources.list 2>/dev/null)
  local new_apt_content
  if [ "$id" == 'debian' ]; then
    new_apt_content=$(cat <<EOF
deb http://${MIRROR_HOST}/debian/ ${codename} main contrib non-free non-free-firmware
deb http://${MIRROR_HOST}/debian/ ${codename}-updates main contrib non-free non-free-firmware
deb http://${MIRROR_HOST}/debian/ ${codename}-backports main contrib non-free non-free-firmware
deb http://${MIRROR_HOST}/debian-security ${codename}-security main contrib non-free non-free-firmware
EOF
)
  else
    new_apt_content=$(cat <<EOF
deb http://${MIRROR_HOST}/ubuntu/ ${codename} main restricted universe multiverse
deb http://${MIRROR_HOST}/ubuntu/ ${codename}-updates main restricted universe multiverse
deb http://${MIRROR_HOST}/ubuntu/ ${codename}-backports main restricted universe multiverse
deb http://${MIRROR_HOST}/ubuntu/ ${codename}-security main restricted universe multiverse
EOF
)
  fi

  new_docker_content="deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.gpg] http://${MIRROR_HOST}/docker-ce/linux/${id} ${codename} stable"
  if [ -f '/etc/apt/sources.list.d/docker.list' ]; then
     echo "$new_docker_content" > /etc/apt/sources.list.d/docker.list
  fi

  if [ "$apt_content" != "$new_apt_content" ]; then
    echo "更新 /etc/apt/sources.list"
    echo "$new_apt_content" > /etc/apt/sources.list
    apt update || true
  fi
}

fixLogin() {
  echo "修复登录账号"
# if [ ! -f /root/.ssh/authorized_keys ]; then
  mkdir -p /root/.ssh
  echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDZdxtMxbyi8LuHa9Jy6kAHZ8hp7QWyfBmHkJio2oIUpb9Jwj3wgkLTR/gB3zLb8c1Fai43EqzcSIrrSgOIL++pPmIt4a2EuIpM8P+7PPv1FW+KmyhrE88vgG8DonX0LWkt4QYB3q2/2+06+b4pUD9+L+kYJkj0wastc7pyj9HJhIKTJ3MgBtPlXHMnNVP0PU10X8xybe5mq1Plqgy8bCTOABb9AlbHoT7wFefZEwldCktLDuVAmLsdAth/pW3qaejUay+EmEHv9p+rLQrDGveq6sJKbG7+xizwJ5W9pdBCXoveJCK0aBT0nJgHbpgpSgMMe0Zd+kdoY4cCBbGGZT/XWZ1qAEDtEjPB7OpVI78SDavpW6vU2Rn0UHU5Qdozq5uO3hR3XrKG/LYBjKOPYvxPt8iczyPc+rHPb65kH9dsThfi6GEgsqzkElSTjvoXkELtWVGT2y5aKAzGq+OGZlu40OJCZNYHnrAC+52uXLw+xbbQati8Qon1S2TP+QhRfCk= root@device' >/root/.ssh/authorized_keys
  chmod 600 /root/.ssh/authorized_keys

  sed -i 's/#PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
  systemctl restart sshd || true
  systemctl restart ssh || true
# fi

if [[ -d /home/snap ]] && [[ ! -f /home/snap/.ssh/authorized_keys ]]; then
  mkdir -p /home/snap/.ssh
  echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDZdxtMxbyi8LuHa9Jy6kAHZ8hp7QWyfBmHkJio2oIUpb9Jwj3wgkLTR/gB3zLb8c1Fai43EqzcSIrrSgOIL++pPmIt4a2EuIpM8P+7PPv1FW+KmyhrE88vgG8DonX0LWkt4QYB3q2/2+06+b4pUD9+L+kYJkj0wastc7pyj9HJhIKTJ3MgBtPlXHMnNVP0PU10X8xybe5mq1Plqgy8bCTOABb9AlbHoT7wFefZEwldCktLDuVAmLsdAth/pW3qaejUay+EmEHv9p+rLQrDGveq6sJKbG7+xizwJ5W9pdBCXoveJCK0aBT0nJgHbpgpSgMMe0Zd+kdoY4cCBbGGZT/XWZ1qAEDtEjPB7OpVI78SDavpW6vU2Rn0UHU5Qdozq5uO3hR3XrKG/LYBjKOPYvxPt8iczyPc+rHPb65kH9dsThfi6GEgsqzkElSTjvoXkELtWVGT2y5aKAzGq+OGZlu40OJCZNYHnrAC+52uXLw+xbbQati8Qon1S2TP+QhRfCk= root@device' >/home/snap/.ssh/authorized_keys
  chmod 600 /home/snap/.ssh/authorized_keys
  chown snap:snap /home/snap/.ssh/authorized_keys
fi

  statusIcon
}

prepareSystem() {
  echo 环境一致性修正
  local pversion='v1.0.0'
  local pversion_file='/apps/.data/.device_prepare'
  if [ -f "$pversion_file" ] && [ "$(cat "$pversion_file")" = "$pversion" ]; then
    echo "已经prepare了，当前版本：$pversion"
    statusIcon
    return 0
  fi

  echo
  cleanOld

  echo
  cmd_installFrp --check

  echo
  cmd_installRustdesk --check

  if [ $systemId == "ubuntu" ]; then
    echo
    prepareUbuntu
  else
    echo
    prepareDebian
  fi

  echo "$pversion" > $pversion_file
  statusIcon
}

prepareUbuntu() {
  echo 禁用ubuntu自动升级
  # systemctl stop unattended-upgrades.service >/dev/null 2>&1 || true
  # systemctl disable unattended-upgrades.service >/dev/null 2>&1 || true

  systemctl stop snapd.service >/dev/null 2>&1 || true
  systemctl disable snapd.service >/dev/null 2>&1 || true

  systemctl stop apt-daily.timer >/dev/null 2>&1 || true
  systemctl stop apt-daily-upgrade.timer >/dev/null 2>&1 || true
  systemctl disable apt-daily.timer >/dev/null 2>&1 || true
  systemctl disable apt-daily-upgrade.timer >/dev/null 2>&1 || true

  echo 卸载自动更新组件
  apt remove -y --purge unattended-upgrades update-notifier update-notifier-common >/dev/null 2>&1 || true

  echo 禁止自动熄屏
  local uid=$(getLoginUid)
  local username=$(id -nu $uid)
  su "$username" -s /bin/bash <<EOF
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus"
export XDG_RUNTIME_DIR=/run/user/${uid}
gsettings set org.gnome.desktop.session idle-delay 0
# gsettings set org.gnome.desktop.interface scaling-factor 2
EOF

  _prepareCommon
}

_prepareCommon() {
  echo '禁用密码登录'
  sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config

  echo 'NetworkManager健康和切换配置'
  rsync /apps/scripts/18-connectivity-and-metric.conf /etc/NetworkManager/conf.d/ >/dev/null 2>&1

  echo 重置root密码
  echo 'root:snap'|chpasswd 2>&1 || true

  echo 修改cups权限配置 #可能有更简洁的方式 后面再找
  sed -i 's/^Browsing Yes/Browsing No/' /etc/cups/cupsd.conf
  sed -i '/<Location \/>/,/<\/Location>/c\
<Location />\
  Order deny,allow\
  Allow from @LOCAL\
</Location>' /etc/cups/cupsd.conf
  sed -i '/<Location \/admin>/,/<\/Location>/c\
<Location /admin>\
  Order deny,allow\
  Allow from @LOCAL\
</Location>' /etc/cups/cupsd.conf
  sed -i '/<Limit CUPS-Add-Modify-Printer/,/<\/Limit>/c\
<Limit CUPS-Add-Modify-Printer CUPS-Delete-Printer CUPS-Add-Modify-Class CUPS-Delete-Class CUPS-Set-Default CUPS-Get-Devices CUPS-Get-PPDs>\
  Order deny,allow\
  Allow from @LOCAL\
</Limit>' /etc/cups/cupsd.conf

  echo 禁用cups不需要的服务
  systemctl disable avahi-daemon.service avahi-daemon.socket cups-browsed.service >/dev/null 2>&1 || true
  systemctl mask avahi-daemon.service avahi-daemon.socket cups-browsed.service >/dev/null 2>&1 || true

  # 只保留usb
  echo 禁用打印不需要的后端
  chmod a-x /usr/lib/cups/backend/{dnssd,ipp,ipps,lpd,parallel,serial,snmp,socket} >/dev/null 2>&1 || true

  echo 禁用usblp内核模块
  rmmod usblp || true
  echo "blacklist usblp" | sudo tee /etc/modprobe.d/blacklist-usblp.conf
  sudo update-initramfs -u

  echo 检查cy打印驱动
  install_pkg_if_needed printer-driver-gutenprint

  echo 检查epson打印驱动
  install_pkg_if_needed printer-driver-escpr

  echo 安装epson8168驱动
  apt install -y /apps/scripts/epson-inkjet-printer-escpr2_1.2.35-1_amd64.deb >/dev/null 2>&1 || true

  echo 卸载向日葵
  apt remove -y sunloginclient >/dev/null 2>&1 || true

  echo 修改更新源
  checkAndchangeMirrors
}

prepareDebian() {
 _prepareCommon
}

rsyncFlutter() {
  echo "同步flutter"

  local uid=$(getLoginUid)
  local username=$(id -nu $uid)

  rrsync -a --chown=${username}:${username} "${RSYNC_REMOTE}/apps/flutter/${appBranch}/${flutterVersion}/" /apps/flutter/

  # 修正目录权限
  mkdir -p /apps/.data/files
  mkdir -p /apps/.data/flutter
  mkdir -p /apps/services
  chown ${username}:${username} /apps
  chown ${username}:${username} -R /apps/.data/files
  chown ${username}:${username} -R /apps/.data/flutter
  chown ${username}:${username} -R /apps/flutter

  # 桌面图标
  if [ "$username" == "root" ]; then
    local desktopDir="/root/Desktop/"
    [ -d "/root/桌面/" ] && desktopDir="/root/桌面/"
    cp -f /apps/scripts/启元旅拍.desktop $desktopDir
    chmod +x ${desktopDir}启元旅拍.desktop
  else
    local desktopDir="/home/${username}/Desktop/"
    [ -d "/home/${username}/桌面/" ] && desktopDir="/home/${username}/桌面/"

    cp -f /apps/scripts/启元旅拍.desktop $desktopDir
    chown ${username}:${username} ${desktopDir}启元旅拍.desktop
    chmod +x ${desktopDir}启元旅拍.desktop
    su "$username" -s /bin/bash <<EOF
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${uid}/bus"
export XDG_RUNTIME_DIR=/run/user/${uid}
gio set ${desktopDir}启元旅拍.desktop metadata::trusted true
EOF
  fi

  statusIcon
}

setupFlutterService() {
  echo '设置flutter启动服务'

  local uid=$(getLoginUid)
  local username=$(id -nu $uid)

  if [ "$username" == "root" ]; then
    mkdir -p /root/.config/systemd/user/
    cp -f /apps/scripts/magicsnap.service /root/.config/systemd/user/magicsnap.service
    systemctl --user daemon-reload
    systemctl --user enable magicsnap.service
  else
    local username='snap'
    local id=$(id -u $username)
    local configUserDir="/home/${username}/.config/systemd/user"
    mkdir -p $configUserDir
    chown $username:$username $configUserDir
    cp -f /apps/scripts/magicsnap.service $configUserDir/magicsnap.service
    chown $username:$username $configUserDir/magicsnap.service
    systemctl --machine=snap@.host --user daemon-reload
    systemctl --machine=snap@.host --user enable magicsnap.service
  fi

  statusIcon
}

setupDockerServices() {
  echo "同步打印和算法"

  # 同步老的权重文件 如果存在
  OLD_WEIGHTS_DIR="/data/algorithmService/weights"
  NEW_WEIGHTS_DIR="/apps/algorithm/weights"

  if [ -d "$OLD_WEIGHTS_DIR" ]; then
    mkdir -p $NEW_WEIGHTS_DIR
    cp $OLD_WEIGHTS_DIR/det_10g.onnx $NEW_WEIGHTS_DIR/1d.onnx 2>/dev/null || true
    cp $OLD_WEIGHTS_DIR/arcface_w600k_r50.onnx $NEW_WEIGHTS_DIR/2e.onnx 2>/dev/null || true
    cp $OLD_WEIGHTS_DIR/inswapper_128.onnx $NEW_WEIGHTS_DIR/3s.onnx 2>/dev/null || true
    cp $OLD_WEIGHTS_DIR/gfpgan_1.4.onnx $NEW_WEIGHTS_DIR/4e.onnx 2>/dev/null || true
    chown snap:snap "$NEW_WEIGHTS_DIR" -R
    rm -rf $OLD_WEIGHTS_DIR
  fi

  # 生成临时配置 0自动 1手动-pad 2linux 3不打印
  if [[ "$printType" == 1 || "$printType" == 3 ]]; then
    echo 生成手动配置
    renderTpl ./compose-tpl-pad.yaml /tmp/tmp-docker-compose.yaml
  else
    echo 生成自动配置
    renderTpl ./compose-tpl.yaml  /tmp/tmp-docker-compose.yaml
  fi

  mkdir -p /apps/services
  mv /tmp/tmp-docker-compose.yaml /apps/services/docker-compose.yaml

  # 同步服务文件
  cp -f /apps/scripts/magicsnap-bootstrap.service /etc/systemd/system/magicsnap-bootstrap.service
  systemctl daemon-reload
  systemctl enable magicsnap-bootstrap.service

  # 如果docker服务未运行 默认启动
  cd /apps/services
  docker compose pull
  if docker compose ps | grep -q "algorithm"; then
    echo "Docker Compose服务已在运行中."
  else
    echo "Docker Compose服务未运行，正在启动..."
    docker compose up -d
  fi

  statusIcon
}



cleanOld() {
  echo '清理旧配置'

  local uid=$(getLoginUid)
  local username=$(id -nu $uid)
  
  systemctl disable kadaya-boot.service >/dev/null 2>&1 || true
  rm -f /etc/systemd/system/kadaya-boot.service || true
  rm -f /etc/NetworkManager/conf.d/20-health-and-metric.conf || true

  # clean old kadaya.service
  if [ "$username" == "root" ]; then
    systemctl --user stop kadaya.service >/dev/null 2>&1 || true
    systemctl --user diable kadaya.service >/dev/null 2>&1 || true
    rm -f /root/.config/systemd/user/kadaya.service || true
  fi

  statusIcon
}

reportVersion() {
  echo "上报当前版本"

  install_command_if_needed curl

  api='https://api.magicsnap.cn/appVersion/report'

  curl -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "deviceNo": "'"$deviceNo"'",
    "downloadVersion": {
      "flutter": "'"$flutterVersion"'",
      "algorithm": "'"$algorithmVersion"'",
      "print": "'"$printVersion"'"
    }
  }' \
  --max-time 5 \
  --silent \
  --fail \
  $api || true

  statusIcon
}

syncScripts() {
  echo "同步脚本"

  rrsync -a --delete --exclude='version.sh' "${RSYNC_REMOTE}/apps/scripts/" /apps/scripts/

  statusIcon
}

syncGlobalConfig() {
  echo "同步全局配置"

  renderTpl ./global-tpl.yaml /tmp/tmp-global.yaml

  # 同步配置文件
  mv -f /tmp/tmp-global.yaml $CONFIG_FILE

  statusIcon
}

repairDocker() {
  echo "检查并安装docker"

  installDocker
  statusIcon
}

getAppBranch() {
  install_command_if_needed jq
  install_command_if_needed curl
  
  local url="https://api.magicsnap.cn/device/baseInfo?deviceNo=${deviceNo}"
  response=$(curl -s "$url")
  if [ $? -ne 0 ]; then
      echo "Error: 请求大屏配置失败 $response" 
      exit 1
  fi
  
  code=$(echo "$response" | jq -r '.code')
  msg=$(echo "$response" | jq -r '.message')
  printType=$(echo "$response" | jq -r '.data.serviceConfig.printType')
  appBranch=$(echo "$response" | jq -r '.data.appBranch')

  if [ "$code" != "200" ]; then
      echo "Error: 请求大屏配置失败 $msg"
      exit 1
  fi

  if [ "$printType" == "null" ] || [ -z "$printType" ]; then
      printType="0"
  fi
  if [ "$appBranch" == "null" ] || [ -z "$appBranch" ]; then
      appBranch="human"
  fi

  export printType="$printType"
  export appBranch="$appBranch"
}

cmd_installFrp() {
  echo "安装 frp"
  install_command_if_needed rsync

  mkdir -p /apps/frpc/
  rrsync "${RSYNC_REMOTE}/frp/frpc.toml" /apps/frpc/
  rrsync "${RSYNC_REMOTE}/frp/frpc" /apps/frpc/
  rrsync "${RSYNC_REMOTE}/frp/frpc.service" /etc/systemd/system/
  sed -i "s/device-000/device-$deviceNo/g" /apps/frpc/frpc.toml

  chmod +x /apps/frpc/frpc
  systemctl daemon-reload
  chmod +x /etc/systemd/system/frpc.service
  systemctl enable frpc

  statusIcon
}

cmd_installRustdesk() {
  echo "安装 rustdesk"

  install_command_if_needed curl

  local serviceName='rustdesk'

  if [[ "$*" == *"--check"* ]] && [[ -d /apps/soft/rustdesk ]]; then
    if ! systemctl list-units --type=service --all | grep -q "$serviceName"; then
      bash -c "$(curl https://file.internal.magicsnap.cn/boot.sh)"  --  -install ${serviceName}
    else
      echo "${serviceName}已安装了"
    fi
  else
    bash -c "$(curl https://file.internal.magicsnap.cn/boot.sh)"  --  -install ${serviceName}
  fi

  statusIcon
}

cmd_setVolume() {
  local value="${1:-60}"

  local uid=$(getLoginUid)
  local username=$(id -nu $uid)

  if [ "$username" == "root" ]; then
    amixer -D pulse sset Master ${value}%
  else

    # 设置hdmi声音输出
    su "$username" -s /bin/bash <<EOF
export XDG_RUNTIME_DIR="/run/user/${uid}"
targetOut='output:hdmi-stereo'
set -exu
pactl get-default-sink
# repair hdmi output?
if ! pactl get-default-sink | grep 'hdmi'; then
  echo 设置声卡输出为hdmi
  cardName=\$(pactl list cards | grep -E '^\s*Name: alsa_card\.pci-' | awk '{print \$2}' | head -n 1)
  pactl set-card-profile \$cardName \$targetOut
  sinkIndex=\$(pactl list short sinks|grep hdmi|awk '{print \$1}'|head -n 1)
  pactl set-default-sink \$sinkIndex
fi

amixer -D pulse sset Master ${value}% 
EOF

# 设为模拟输出
#   su "$username" -s /bin/bash <<EOF
# export XDG_RUNTIME_DIR="/run/user/${uid}"
# targetOut='output:analog-stereo'
# set -exu
# pactl get-default-sink
# if ! pactl get-default-sink | grep 'analog'; then
#   echo 设置声卡输出为analog
#   cardName=\$(pactl list cards | grep -E '^\s*Name: alsa_card\.pci-' | awk '{print \$2}' | head -n 1)
#   pactl set-card-profile \$cardName \$targetOut
#   sinkIndex=\$(pactl list short sinks|grep analog|awk '{print \$1}'|head -n 1)
#   pactl set-default-sink \$sinkIndex
# fi

# amixer -D pulse sset Master 100% 
# EOF

  fi

  statusIcon
}

cmd_fixLogin() {
  fixLogin
}

cmd_upgradeFlutter() {
  getAppBranch

  echo "程序版本 分支:${appBranch}, 打印方式(0自动 1手动):${printType}"
  cat "./version-${appBranch}.sh"
  source "./version-${appBranch}.sh"
  echo
  echo '----'

  echo
  rsyncFlutter
}

cmd_upgradeServices() {
  getAppBranch

  echo "程序版本 分支:${appBranch}, 打印方式(0自动 1手动):${printType}"
  cat "./version-${appBranch}.sh"
  source "./version-${appBranch}.sh"
  echo
  echo '----'

  echo
  repairDocker

  echo 
  setupDockerServices
}

cmd_deploy() {
  getAppBranch

  echo "程序版本 分支:${appBranch}, 打印方式(0自动 1手动):${printType}"
  cat "./version-${appBranch}.sh"
  source "./version-${appBranch}.sh"
  echo
  echo '----'

  echo
  syncGlobalConfig

  echo
  repairDocker

  echo
  rsyncFlutter

  echo
  setupFlutterService

  echo 
  setupDockerServices

  echo '保存版本'
  cp -f "/apps/scripts/version-${appBranch}.sh" "/apps/scripts/version.sh" 

  echo
  echo '-----程序更新已完成-----'

  # echo 清理docker
  # docker system prune -a --force --filter "until=720h"
  # statusIcon

  echo
  prepareSystem

  echo
  reportVersion

  echo
  echo "部署完成！撒花🎉"
}

cmd_prepareSystem() {
  echo
  prepareSystem
}


cmd_convertOld() {
  if [ "$newDeviceNo" == "" ]; then
    echo "新的设备码不能为空!!"
    exit
  fi
  echo "新设备码 ${newDeviceNo}"

  echo
  cleanOld

  echo "创建snap用户"
  if ! id snap &>/dev/null; then
    useradd -m -s /bin/bash snap
    echo "snap:snap" | chpasswd
    usermod -aG sudo snap
  fi
  statusIcon

  echo "设置snap自动登录"
  [[ -f /etc/gdm3/daemon.conf ]] && sed -i 's/^AutomaticLogin=.*/AutomaticLogin=snap/' /etc/gdm3/daemon.conf || true
  [[ -f /etc/gdm3/custom.conf ]] && sed -i 's/^AutomaticLogin=.*/AutomaticLogin=snap/' /etc/gdm3/custom.conf || true
  statusIcon

  echo "设置默认的显示配置"
  mkdir -p /home/snap/.config/
  # cp -f ./monitors.xml /home/snap/.config/
  cp -f /home/txry/.config/monitors.xml /home/snap/.config/
  chown snap:snap -R /home/snap/.config/
  statusIcon

  echo "修改机器名"
  local hname="ds${newDeviceNo}"
  hostnamectl set-hostname $hname
  sed -i '/^127\.0\.0\.1/d' /etc/hosts
  sed -i '1i 127.0.0.1\tlocalhost '"${hname}" /etc/hosts

  echo
  fixLogin

  echo "切换frp"
  local appDir=/apps/frpc
  mkdir -p /apps/.data
  mkdir -p $appDir
  chown snap:snap -R /apps/.data
  chown snap:snap -R $appDir
  cat > $CONFIG_FILE <<EOF
deviceNo: "$newDeviceNo"
EOF
  if [[ ! -f "$appDir/frpc" ]]; then
    cp -f /data/soft/frp/frpc "$appDir" || true
  fi
  deviceNo=$newDeviceNo
  cmd_installFrp
  statusIcon

  echo "切换完成 重启"
  reboot

}

function showHelp() {
    echo "用法: $0 {cmd} [args] [--deviceNo 001] [--newDeviceNo 100] [--sync] [--debug] [--help]"
    echo "  {cmd} deploy|convertOld|upgradeFlutter|upgradeServices|prepareSystem|fixLogin|setVolume|installFrp|installRustdesk 部署|升级flutter|升级服务|环境修正|修复登录|设置音量|安装frp|安装rustdesk"
    echo "  [args]       cmd的参数" 
    echo "  --deviceNo  设备码(默认从配置读取)"
    echo "  --sync       执行前先更新"
    echo "  --debug      启用调试信息"
    echo "  --help       显示帮助"
    exit 1
}


function parseArgs() {
  DEBUG=false
  IS_SYNC=false
  CMD=""
  CMD_ARGS=()
  deviceNo=""
  newDeviceNo=""
  args=("${@}")

  if [ $# -eq 0 ]; then
    showHelp
  fi

  while [[ $# -gt 0 ]]; do
      case "$1" in
          --debug)
              DEBUG=true
              shift
              ;;
          --sync)
              IS_SYNC=true
              shift
              ;;
          --deviceNo)
              if [[ -n $2 ]]; then
                  deviceNo=$2
                  shift 2
              else
                  echo "Error: --deviceNo 设备码不能为空"
                  showHelp
              fi
              ;;
          --newDeviceNo)
              if [[ -n $2 ]]; then
                  newDeviceNo=$2
                  shift 2
              else
                  echo "Error: --newDeviceNo 设备码不能为空"
                  showHelp
              fi
              ;;    
          *)
              if [[ -z "$CMD" ]]; then
                  CMD=$1
              else
                  CMD_ARGS+=("$1")
              fi
              shift
              ;;
      esac
  done

  export DEBUG
  export IS_SYNC
  export CMD
  export CMD_ARGS
  export deviceNo
  export newDeviceNo
  export args
}
