#!/usr/bin/env bash

#常用变量
#指定内署dll或windows dll，b=builtin(wine)，n=native(windows)
#export WINEDLLOVERRIDES="bass=n,z:\\sdcard\\xinhao\\games\\unplay\\zw\\bass=b"
#for i in /usr/lib/wine/winepulse.drv.so /usr/lib/wine/fakedlls/winepulse.drv /usr/lib32/wine/fakedlls/winepulse.drv /usr/lib32/wine/winepulse.drv.so; do chmod 000 "$i"; chattr +i "$i"; done
#Exec=box86 wine explorer /desktop=name,1024x768 /sdcard/xinhao/games/War3/Frozen\ Throne.exe %f
#QT_SCREEN_SCALE_FACTORS=1
#BOX86_PATH=
#BOX86_LD_LIBRARY_PATH=
#export BOX64_PATH=${HOME}/wine64/bin/
#export BOX64_LD_LIBRARY_PATH=${HOME}/wine64/lib/wine/i386-unix/:${HOME}/wine64/lib/wine/x86_64-unix/:/lib/i386-linux-gnu/:/lib/x86_64-linux-gnu:/lib/aarch64-linux-gnu/
#默认系统盘目录export WINEPREFIX="${HOME}/.wine"
#opengl的驱动路径 LIBGL_DRIVERS_PATH=${HOME}/wine/usr/lib/i386-linux-gnu/dri
#GALLIUM_DRIVER=llvmpipe,zink
#export LIBGL_ALWAYS_SOFTWARE=1
#native用的是arm的lib
#DXVK_ASYNC=1 WINE_FULLSCREEN_FSR=1
#Force DirectX 11.0 feature level 9.1: -force-feature-level–9–1
#Force single threaded rendering: -force-gfx-direct
:<<\debug
+all:输出所有通道。
+heap:追踪栈信息。
+loaddll:输出每个被加载的dll信息。
+message:
+msgbox:
+pid:进程
+relay:输出build-in DLL间的跨dll函数调用。注意与dll内的单个模块内的Channel区别开。
+seh:输出Windows结构化异常处理信息。
+server:
+snoop:输出native DLL间的跨dll函数调用。
+synchronous:
+timestamp:
+fps:
debug
#Force DirectX 11.0 to be created without D3D11_CREATE_DEVICE_SINGLETHREADED flag: -force-d3d11-no-singlethreaded
#Force DirectX 11.0 feature level 10.0: -force-feature-level–10–0
#for i in $(sed 's@\./@/@g' /usr/share/doc/wine/postrm | sed ':a;N;s/\n/ /g;ta'); do if [ -f "$i" ]; then rm -v $i; fi done
:<<-eof
高位色运行低位色
Xephyr :1 -ac -screen 640x480x16 -reset -terminate &
DISPLAY=:1 openbox &
DISPLAY=:1 box86 wine start /unix /sdcard/xinhao/games/samurai2/SAMURAI2.EXE
eof
#SIGILL: 执行了非法指令. 通常是因为可执行文件本身出现错误, 或者试图执行数据段. 堆栈溢出时也有可能产生这个信号。
#SIGSEGV(Segment fault)意味着指针所对应的地址是无效地址，没有物理内存对应该地址，由于对合法存储地址的非法访问触发的(如访问不属于自己存储空间或只读存储空间)。试图访问未分配给自己的内存, 或试图往没有写权限的内存地址写数据.

case $(dpkg --print-architecture) in
        aarch64|arm64) echo "" ;;
	*) echo -e "\e[31m不支持你的架构\e[0m"
                sleep 2
                exit 0
esac

#容器，可选 jammy bullseye kali sid kali_org
ROOTFS=sid

#box安装方式，可选 REPO GIT RELEASE XB6868 NOBOX
BOX_INSTALL=XB6868
#box_update box86最后更新时间:20230628
#box_update box64最后更新时间:20230322

#wine安装方式，注意：REPO仅对bullseye可用，可选 REPO PLAYONLINUX XB6868 NOWINE
WINE_INSTALL=XB6868
#wine_version 最后更新版本为8.13

#自定义容器名字
NAME=wine-arm64

CONTAINER=".${NAME}"

START=start-${NAME}
case $ROOTFS in
impish|jammy)
LXC=ubuntu
DEB="main restricted universe multiverse"
;;
bullseye)
LXC=debian
DEB="main contrib non-free"
;;
sid)
LXC=debian
DEB="main contrib non-free non-free-firmware"
;;
kali)
LXC=kali
ROOTFS=current
DEB="main contrib non-free"
WINE_INSTALL=XB6868
;;
kali_org)
LXC=kali
DEB="main contrib non-free"
WINE_INSTALL=PLAYONLINUX
esac
URL="https://mirrors.tuna.tsinghua.edu.cn"
cd

if [ $(uname -o) != Android ]; then echo -e "\e[33m仅适用于termux环境\e[0m"; sleep 1; exit 0; fi

echo -e "\e[33m检测环境..\e[0m"
sleep 1
clear
pkg up -y && yes|pkg upgrade
dpkg -l termux-x11-nightly|grep -q ii; if [ $? = 1 ]; then pkg i x11-repo -y&&pkg i termux-x11-nightly -y; fi
pkg i -y curl proot tar pulseaudio wget mesa virglrenderer-android
if [ ! $(command -v proot) ]; then
echo -e "\e[33m检测环境失败，安装中止\e[0m"
sleep 1
exit 0
fi
unset i
if [ -d ${CONTAINER} ]; then echo -e "\n检测已有相关文件夹，是否删除？\n\e[33m1) 删除重装\n2) 删除\n0) 退出\e[0m\n";
read -r -p "请选择: " input
case $input in
1) rm -rf ${CONTAINER} ;;
2) rm -rf ${CONTAINER} ${PREFIX}/bin/start-${CONTAINER}
echo -e "\e[33m已御载${NAME}\e[0m"
sleep 1
exit 0 ;;
*) exit 0
esac
fi
echo -e "\n\n\e[33m本脚本为支持proot容器运行windows exe的32位与64位程序\n\n由于最近容器发行版架构存在冲突问题，故改为恢复包下载，即将下载系统\e[0m"
sleep 3

rm boxwine.tar.xz 2>/dev/null
wget https://shell.xb6868.com/wine/boxwine.tar.xz
echo -e "\e[33m检测包下载完整性\e[0m"
if [[ $(du -b boxwine.tar.xz|awk '{print $1}') != $(curl -I https://shell.xb6868.com/wine/boxwine.tar.xz|grep -i length|awk '{print $2}'|sed "s/\r//") ]]; then echo -e "\e[31m下载的包并不完整，但不会中止此次操作，如果安装失败，建议切换网络重新执行此脚本，\e[0m"; read -p "回车键继续"; fi

tar Jxvf boxwine.tar.xz

echo -e "\e[33m系统已下载,文件夹名为${CONTAINER}\e[0m"
echo -e "登录命令为\e[33m${START}\e[0m"
sleep 5

cat >${CONTAINER}/root/firstrun<<-'eof'
#!/usr/bin/env bash

URL="https://mirrors.tuna.tsinghua.edu.cn"
echo -e "\n\e[33m正在配置初始化\n\e[0m"
sleep 1

if [ -f /opt/wine-devel/bin/wine ] || [ -f /root/wine/opt/wine-devel/bin/wine ] || [ -f /root/wine/bin/wine ] && [ $(command -v box64) ] && [ $(command -v box86) ]; then
if [ ! -f /usr/local/bin/winetricks ]; then
echo -e "\n\e[33m下载 winetricks\e[0m\n"
sleep 1
curl https://ghproxy.com/https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks -o /usr/local/bin/winetricks
if [ -f /usr/local/bin/winetricks ]; then
#sed -i '2a export WINEARCH=win32 BOX64_NOBANNER=1 BOX86_NOBANNER=1 WINEDEBUG=fixme-all' /usr/local/bin/winetricks
sed -E -i 's/GitHub.*似乎不是个有效的版本号(.*)/执行文件检测试中\1/' /usr/local/bin/winetricks
sed -E -i "s/(latest_version=).*winetricks.*/\1$(grep 'WINETRICKS_VERSION=' /usr/local/bin/winetricks|cut -d = -f2)/;/I_run_Wine_as_root.3F/s/w_warn/echo/;/supported upstream/s/w_warn/echo/" /usr/local/bin/winetricks
curl --connect-timeout 5 -m 8 -s https://github.com/Winetricks/ >/dev/null
if [ $? == 1 ]; then
echo -e "\e[33m你的网络无法访问github，将为你添加代理\e[0m"
sleep 2
sed -i 's/github/kgithub/g;s@https.*raw.kgithub@https://ghproxy.com/https://raw.github@' /usr/local/bin/winetricks
fi
#sed -i "/latest_version=.*winetricks.*/s/^/#/" /usr/local/bin/winetricks
#sed -E -i "s/(latest_version=.*winetricks.*)/^/#/" /usr/local/bin/winetricks
chmod a+x /usr/local/bin/winetricks
mkdir -p ${HOME}/.cache/winetricks/ 2>/dev/null
echo 0 >${HOME}/.cache/winetricks/track_usage
fi
fi

BIN_PATH=$(find /root/wine/ -name wineserver -type f)
if [ -n $BIN_PATH ]; then
rm /usr/local/bin/wine /usr/local/bin/wine64 /usr/local/bin/wineserver /usr/local/bin/winecfg /usr/local/bin/wineboot 2>/dev/null
if [ -f "${BIN_PATH%/*}"/wine64 ]; then
echo -e "#!/bin/sh
box64 "${BIN_PATH%/*}"/wineserver \"\$@\"" >/usr/local/bin/wineserver
else
echo -e "#!/bin/sh
box86 "${BIN_PATH%/*}"/wineserver \"\$@\"" >/usr/local/bin/wineserver
sed -i 's/wine64/wine/' /usr/local/bin/boxwine* 2>/dev/null
fi
echo -e "#!/bin/sh
box86 "${BIN_PATH%/*}"/wine \"\$@\"" >/usr/local/bin/wine
echo -e "#!/bin/sh
box64 "${BIN_PATH%/*}"/wine64 \"\$@\"" >/usr/local/bin/wine64
ln -sf "${BIN_PATH%/*}"/winecfg /usr/local/bin
ln -sf "${BIN_PATH%/*}"/wineboot /usr/local/bin
chmod a+x /usr/local/bin/wine /usr/local/bin/wine64 /usr/local/bin/wineserver /usr/local/bin/winecfg /usr/local/bin/wineboot
fi

echo -e "\e[33m进行wine初始化配置，等待时间比较长…\e[0m"
sleep 1
rm -rf .wine 2>/dev/null
sleep 5
if [ -f "${BIN_PATH%/*}"/wine64 ] && [[ $(echo "$(wine64 --version)"|tail -1|cut -b 6) == [4-7] ]]; then
export BOX86_DYNAREC=0
wineboot 2>/dev/null &
pkill services
sed -i "/boxwine/a sleep 5\npkill services" /usr/local/bin/start*
else
wineboot 2>/dev/null
fi
pstree | grep -q "services"
while [ $? == 0 ]
do
sleep 1
pstree | grep -q "services"
done

while [ ! -f .wine/user.reg ]
do
sleep 1
done
while ! grep Desktops .wine/user.reg
do
sleep 1

sed -i '/\[Environment/i \[Software\\\\Wine\\\\Explorer\]\n"Desktop"="Default"\n\n\[Software\\\\Wine\\\\Explorer\\\\Desktops\]\n"Default"="800x600"\n\n\[Software\\\\Wine\\\\X11 Driver\]\n"Decorated"="N"\n"Managed"="Y"\n\n\[Software\\\\Wine\\\\Drivers\]\n"Audio"="alsa"\n\n' .wine/user.reg

done

#Disable the GUI crash dialog
sed -i '/X11/i [Software\\Wine\\WineDbg]\n"ShowCrashDialog"=dword:00000000\n' ${HOME}/.wine/user.reg

sed -i '/FontMapper/i \[Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\FontLink\\\\SystemLink\]\n"Arial"="wqy-microhei.ttc"\n"Arial Black"="wqy-microhei.ttc"\n"Lucida Sans Unicode"="wqy-microhei.ttc"\n"MS Sans Serif"="wqy-microhei.ttc"\n"SimSun"="wqy-microhei.ttc"\n"Tahoma"="wqy-microhei.ttc"\n"Tahoma Bold"="wqy-microhei.ttc"\n\n' .wine/system.reg
fi

pstree | grep -q "services"
if [ $? == 0 ]; then
pkill services
fi
echo -e "\e[33m配置中，请稍候..\e[0m"
pstree | grep -q "wineboot"
while [ $? == 0 ]
do
sleep 3
du -sh ${HOME}/.wine
pstree | grep -q "wineboot"
done
#WINEDEBUG=fps,fixme-all
echo -e "\n\e[33m配置完毕\e[0m\n"
echo -e "\n如果上面的安装失败,请输\e[33mbash firstrun\e[0m重新安装"

if [ -f /opt/wine-devel/bin/wine ] || [ -f /root/wine/opt/wine-devel/bin/wine ] || [ -f /root/wine/bin/wine ] && [ $(command -v box64) ] && [ $(command -v box86) ]; then

echo -e "登录本系统，请输\e[33mstart-wine-arm64\e[0m"
#\nvnc打开wine请输\e[33mstartwine\e[0m，vnc viewer地址输127.0.0.1:0\nxsdl打开wine\e[33m请先打开xsdl\e[0m，再输\e[33mstartxsdl\e[0m\n修改分辨率适配游戏，请输\e[33mfbl\e[0m\n\e[0m\n使用图形winetricks输\e[33mstartricks\e[0m\n关于startwine更多帮助，请输\e[33mstartwine help\e[0m\n"
fi
read -p "确认请回车"
sed -i "/firstrun/d" /etc/profile
clear
source /root/.bashrc
exit 0
eof
echo "bash firstrun" >>${HOME}/${CONTAINER}/etc/profile
#If no 'isolated_environment', the following host directories will be available:


sed -i "2i WINE_VERSION=$WINE_VERSION" ${CONTAINER}/root/firstrun
sed -i "2i ROOTFS=$ROOTFS" ${CONTAINER}/root/firstrun
sed -i "2i BOX_INSTALL=$BOX_INSTALL" ${CONTAINER}/root/firstrun
sed -i "2i LXC=$LXC" ${CONTAINER}/root/firstrun
sed -i "2i WINE_INSTALL=$WINE_INSTALL" ${CONTAINER}/root/firstrun
sed -i "2i START=$START" ${CONTAINER}/root/firstrun
sed -i "2i NOR_USER=$NOR_USER" ${CONTAINER}/root/firstrun
sed -i '/=$/d' ${HOME}/${CONTAINER}/etc/profile

if [ -z $ANDROID_RUNTIME_ROOT ]; then
export ANDROID_RUNTIME_ROOT=/apex/com.android.runtime
fi
cat >>${HOME}/${CONTAINER}/etc/profile<<-EOF
export ANDROID_ART_ROOT=${ANDROID_ART_ROOT-}
export ANDROID_DATA=${ANDROID_DATA-}
export ANDROID_I18N_ROOT=${ANDROID_I18N_ROOT-}
export ANDROID_ROOT=${ANDROID_ROOT-}
export ANDROID_RUNTIME_ROOT=${ANDROID_RUNTIME_ROOT-}
export ANDROID_TZDATA_ROOT=${ANDROID_TZDATA_ROOT-}
export BOOTCLASSPATH=${BOOTCLASSPATH-}
export COLORTERM=${COLORTERM-}
export DEX2OATBOOTCLASSPATH=${DEX2OATBOOTCLASSPATH-}
export EXTERNAL_STORAGE=${EXTERNAL_STORAGE-}
export PATH=\${PATH}:/data/data/com.termux/files/usr/bin:/system/bin:/system/xbin
export PREFIX=${PREFIX-/data/data/com.termux/files/usr}
export TERM=${TERM-xterm-256color}
export TMPDIR=/tmp
export PULSE_SERVER=tcp:127.0.0.1:4713
export BOX86_LOG=0 BOX86_NOBANNER=1 BOX86_NOPULSE=1 BOX64_NOPULSE=1 BOX64_LOG=0 BOX64_NOBANNER=1 WINEDEBUG=fixme-all
EOF

cat >${PREFIX}/bin/start-${NAME}<<eof
#!/usr/bin/env bash
cd
pkill -9 pulseaudio 2>/dev/null
#pkill -f "app_process / com.termux.x11"
bash .wine-aarch64/virapi/startvirgl
pulseaudio --start --load="module-native-protocol-tcp auth-ip-acl=127.0.0.1 auth-anonymous=1" --exit-idle-time=-1 &
unset LD_PRELOAD
proot --kill-on-exit -b /vendor -b /system -b /sdcard -b /sdcard:/root/sdcard -b /data/data/com.termux/files -b /data/data/com.termux/cache -b /data/data/com.termux/files/usr/tmp:/tmp -b /dev/null:/proc/sys/kernel/cap_last_cap -b /data/dalvik-cache -b ${CONTAINER}/tmp:/dev/shm -b /proc/self/fd/2:/dev/stderr -b /proc/self/fd/1:/dev/stdout -b /proc/self/fd/0:/dev/stdin -b /proc/self/fd:/dev/fd -b /dev/urandom:/dev/random --sysvipc --link2symlink -S ${CONTAINER} -w /root /usr/bin/env -i HOME=/root PATH=/usr/local/sbin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/games:/usr/local/games LANG=zh_CN.UTF-8 TZ=Asia/Shanghai TERM=xterm-256color USER=root /bin/bash --login
pkill -f "app_process / com.termux.x11"
pkill -9 libvirglrendere
pkill -9 virgl_test_serv
eof
for i in version misc buddyinfo kmsg consoles execdomains stat fb filesystems loadavg key-users uptime devices vmstat; do if [ ! -r /proc/"${i}" ]; then sed -E -i "s@(cap_last_cap)@\1 -b ${CONTAINER}/etc/proc/${i}:/proc/${i}@" ${PREFIX}/bin/start-${NAME}; fi done
for i in /data/app /system_ext /linkerconfig/com.android.art/ld.config.txt /linkerconfig/ld.config.txt /plat_property_contexts /property_contexts /apex /odm /data/misc/apexdata/com.android.art/dalvik-cache /odm /product /data/data/com.termux/files/apps ; do if [ -e $i ]; then sed -i "s@shm@shm \-b ${i}@" ${PREFIX}/bin/start-${NAME}; fi done

proot --help | grep -q sysvipc
if [ $? == 1 ]; then
sed -i 's/--sysvipc//' ${PREFIX}/bin/start-wine64 ${PREFIX}/bin/start-${NAME} ${PREFIX}/bin/start-$(whoami) 2>/dev/null
fi
rm boxwine.tar.xz
chmod a+x ${PREFIX}/bin/start-${NAME} 2>/dev/null
. ${PREFIX}/bin/start-${NAME}
