#!/usr/bin/bash

CHECKFILE="$WINEPREFIX/VERSION"

ensure_kysec() {
    command -v /usr/sbin/kysec_get >/dev/null 2>&1 && \
    command -v /usr/sbin/kysec_set >/dev/null 2>&1
}

if ensure_kysec && [ -f "$CHECKFILE" ]; then
  # 获取文件内容
  file_content=$(/usr/sbin/kysec_get "$CHECKFILE" 2>/dev/null)

  # 检查是否获取成功
  if [ $? -ne 0 ]; then
      echo "Error: Failed to get content from $CHECKFILE using /usr/sbin/kysec_get." >&2
  fi

  # 检查是否已包含 "verified"
  if ! echo "$file_content" | grep -q "verified"; then
      # 设置为 verified
      echo "Generating security tag for user $USER ......."
      if [[ "$LANG" == *"zh_CN"* || "$LC_ALL" == *"zh_CN"* ]]; then
        start-check -i "正在为用户 $USER 生成安全标签" -t 80 -k "$WINEPREFIX"
      else
        start-check -i "Generating security tag for user $USER"  -t 80 -k "$WINEPREFIX"
      fi

      # 加载 os-release 文件中的变量
      source /etc/os-release

      # 将 VERSION_ID 转为小写，便于忽略大小写比较
      VERSION_ID_LOWERCASE=$(echo "$VERSION_ID" | tr '[:upper:]' '[:lower:]')

      # 判断是否以 "v11" 开头（忽略大小写）
      if [[ "$VERSION_ID_LOWERCASE" == v11* ]]; then
        find "$WINEPREFIX" -type d -print0 | xargs -0 -P $(nproc) -I {} /usr/sbin/kysec_set -rn exectl -v verified {}
      else
        if ! /usr/sbin/kysec_set -rn exectl -v verified "$WINEPREFIX"; then
            echo "Error: /usr/sbin/kysec_set failed." >&2
            # exit 1
        fi
      fi
  fi
fi

SELF=$(readlink -f "$0")
LIBWINE=$(dirname $SELF)/../lib

export PATH=$(dirname $SELF):$PATH
export WINEDLLPATH=${LIBWINE}

. x86_64.env
ulimit -n 100000 &> /dev/null
exec wine "$@"
