#!/usr/local/bin/bash

# -----------------------------------------------------------------------
# Copyright (c) 2019-2025 Alexander Vereeken <Alexander88207>. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# User-friendly Wine front-end

# Wings that can't fly still have a purpose, because no matter what happens
# they still hold the memories of being able to fly.

# -----------------------------------------------------------------------

# Don't Run it as root

if [ $(id -u) -eq 0 ]
then
echo "Running it as root is unsupported and insecure."
exit
fi

# General
export NAME=Mizutamari
export EXECNAME=Mizuma
export VER="2025.06"
export DBIN=fetch
export WINEDLLOVERRIDES=winemenubuilder.exe=d

# Create Configuration file
if [ ! -f "$HOME/.config/$NAME.conf" ]; then
TODO=Configuration
echo "# Specify the home of $NAME" >> $HOME/.config/$NAME.conf
echo "ProjectPath=$HOME/.local/share/$NAME" >> $HOME/.config/$NAME.conf
echo "# Specify the default wine" >> $HOME/.config/$NAME.conf
echo "DefaultWinePath=/usr/local/bin" >> $HOME/.config/$NAME.conf
echo "# Automatically turn the compositor off/on. Brings little better performance and is needed for FreeSync." >> $HOME/.config/$NAME.conf
echo "MetacityCompoSwitch=Off" >> $HOME/.config/$NAME.conf
echo "MATECompoSwitch=Off" >> $HOME/.config/$NAME.conf
echo "XFWMCompoSwitch=Off" >> $HOME/.config/$NAME.conf
echo "KDECompoSwitch=Off" >> $HOME/.config/$NAME.conf
echo "# Turn this off if you don't want to get notifications about using the fallback driver." >> $HOME/.config/$NAME.conf
echo "Creates a backup of the prefix registry if an unsafe shutdown has occurred, please save them immediately after such a situation." >> $HOME/.config/$NAME.conf
echo "BackupPrefixRegistry=Off" >> $HOME/.config/$NAME.conf
echo "# If you do not want to be asked for the configuration of the things below, set this option to Yes or No, depending on your needs." >> $HOME/.config/$NAME.conf
echo "DXVK_Always=Ask" >> $HOME/.config/$NAME.conf
echo "VKD3D_Proton_Always=Ask" >> $HOME/.config/$NAME.conf
echo "# Wine version settings per application." >> $HOME/.config/$NAME.conf
anr=$(yad --question --width=400 --window-icon=$ICO --title "$NAME - $TODO" --text "A new $NAME configuration file have been created, do you want to review it?"; echo $?)
if [[ $anr == *"0"* ]]; then
content=$(yad --text-info --width=1000  --height=500 --filename=$HOME/.config/$NAME.conf --editable --window-icon=$ICO --title "$NAME - $TODO" --text "Close this window if you are done editing.")
[ $? -eq 0 ] && echo "$content" > $HOME/.config/$NAME.conf
fi
fi

# Read Configuration file
export ProjectPath=$(grep ProjectPath $HOME/.config/$NAME.conf | cut -f2 -d"=")
export DefaultWinePath=$(grep DefaultWinePath $HOME/.config/$NAME.conf | cut -f2 -d"=")
AllowLib32Maintenance=$(grep AllowLib32Maintenance $HOME/.config/$NAME.conf | cut -f2 -d"=")
export MetacityCompoSwitch=$(grep MetacityCompoSwitch $HOME/.config/$NAME.conf | cut -f2 -d"=")
export MATECompoSwitch=$(grep MATECompoSwitch $HOME/.config/$NAME.conf | cut -f2 -d"=")
export XFWMCompoSwitch=$(grep XFWMCompoSwitch $HOME/.config/$NAME.conf | cut -f2 -d"=")
export KDECompoSwitch=$(grep KDECompoSwitch $HOME/.config/$NAME.conf | cut -f2 -d"=")
BackupPrefixRegistry=$(grep BackupPrefixRegistry $HOME/.config/$NAME.conf | cut -f2 -d"=")
export DXVK_Always=$(grep DXVK_Always $HOME/.config/$NAME.conf | cut -f2 -d"=")
export VKD3D_Proton_Always=$(grep VKD3D_Proton_Always $HOME/.config/$NAME.conf | cut -f2 -d"=")
export Shortcut_Always=$(grep Shortcut_Always $HOME/.config/$NAME.conf | cut -f2 -d"=")

# Attach subdirectories to the $ProjectPath
export DDIR=$ProjectPath/Data
export LDIR=$ProjectPath/Library
export GDIR=$ProjectPath/Games
export PDIR=$ProjectPath/Programs
export CDIR=$ProjectPath/Cache

if [ ! -d "$ProjectPath" ]; then
mkdir -p $ProjectPath
SC=$(yad --question --width=400 --window-icon=$ICO --title "$NAME - $TODO" --text  "Do you want a shortcut of $NAME in your desktop application menu?" ; echo $?)
if [[ $SC == *"0"* ]]; then
if [ ! -d "$HOME/.local/share/applications" ]; then
mkdir $HOME/.local/share/applications
fi
echo "[Desktop Entry]
Comment=User-friendly Wine front-end
Exec=bash /usr/local/bin/$EXECNAME
Icon=$CDIR/$NAME.png
Categories=Game;
Name=$NAME
StartupNotify=false
Terminal=false
TerminalOptions=
Type=Application
" >> $HOME/.local/share/applications/$NAME.desktop 
if [[ $SC == *"1"* ]]; then 
echo "Shortcut will be not created"
fi
fi
fi

# Library loader
function library-loader {
TODO="Library"
mkdir -p $LDIR
cd $LDIR
$DBIN https://codeberg.org/Alexander88207/Mizutamari/archive/main.zip
7zz x main.zip
mv $LDIR/mizutamari/Library/* $LDIR
cd $LDIR/
rm -r -d $LDIR/mizutamari
rm main.zip
if [ "$(ls -A $LDIR)" ]; then
echo -e "\e[3;5;0;32mLibrary successfully loaded.\e[30;48;5;82m\e[0m"
echo "Library successfully loaded"
else
warn "The library could not be loaded successfully, check your internet connection?"
exec $EXECNAME
fi
}

if [ ! -d "$LDIR" ]; then
library-loader
fi

if [ -z "$( ls -A $LDIR ) " ]; then
library-loader
fi

# Creating the subdirectories if needed.
if [ ! -d "$GDIR" ]; then
mkdir $GDIR
fi

if [ ! -d "$PDIR" ]; then
mkdir $PDIR
fi

if [ ! -d "$DDIR" ]; then
mkdir $DDIR
fi

if [ ! -d "$CDIR" ]; then
mkdir $CDIR
fi

function download {
	cd $CDIR && $DBIN $1
}

function remove {
    rm -d -r -f "$1"
}


# Icon
export ICO=$CDIR/$NAME.png
if [ ! -f "$ICO" ]; then
download https://codeberg.org/Alexander88207/$NAME/raw/branch/main/Media/$NAME.png
fi

# Applists
APPLIST=$(cd $LDIR && ls | grep -v README.md )
APPINST=$(cd "$GDIR" && ls && cd "$PDIR" && ls )

# 4GB Patch to patch executables for LAA
if [ ! -f $DDIR/4gb_patch.exe ]; then
cd $DDIR
$DBIN https://ntcore.com/files/4gb_patch.zip
7zz x 4gb_patch.zip
rm 4gb_patch.zip
fi

function LAA_Patch {
$WINEBIN $DDIR/4gb_patch.exe "$1"
}

function wineverread {
WINEPATH=$(grep $APPNAME-WINEVER $HOME/.config/$NAME.conf | cut -f2 -d"=")
if [[ -z $WINEPATH ]]; then
echo -e "\e[3;5;0;36mWine version has been not set for this application yet, using default wine version from the Mizutamari configuration.\e[30;48;5;82m\e[0m"
echo "$APPNAME-WINEVER=$DefaultWinePath" >> $HOME/.config/$NAME.conf
wineverread
fi
export WINEBIN="$WINEPATH/wine"
export WINE=$WINEPATH/wine
export WINEPATH
}

function warn {
               yad --warning --width=400 --window-icon=$ICO --title "$NAME - $TODO" --text "$1"
           }

function question {
               yad --question --width=400 --window-icon=$ICO --title "$NAME - $TODO" --text "$1"; echo $?
           }

# Advanced Exit
function aexit {
if [ -t 0 ] ; then
echo "Thanks for using $NAME."
fi
if [ -z "$CLI" ]
then
exec $EXECNAME
else
exit
fi
}

# Export functions
export -f question
export -f download
export -f LAA_Patch
export -f remove
export -f warn

function setwineprefix {
if [ ! -f $LDIR/$APPNAME ];
then
warn "Sorry but $APPNAME is not included in the library. Maybe a typo?"
aexit
fi
if [ "$TODO" = "Launcher" ] || [ "$TODO" = "99" ] || [ "$TODO" = "97" ] || [ "$TODO" = "98" ] || [ "$SAM" = "Patch an executable for LAA" ]; then
if [[ $APPINST != *"$APPNAME"* ]]; then
echo "$APPNAME is not installed."
aexit
fi
fi
Game=$(grep Game $LDIR/$APPNAME | cut -f2 -d"=")
Program=$(grep Program $LDIR/$APPNAME | cut -f2 -d"=")
if [[ $Game == *"Yes"* ]]; then
export APPDIR=$GDIR/$APPNAME
fi
if [[ $Program == *"Yes"* ]]; then
export APPDIR=$PDIR/$APPNAME
fi
export WINEPREFIX="$APPDIR"
}

function installdialog {
export TODO=Installation
if [ -z "$CLI" ]
then
export APPNAME=$(yad --select-action="/bin/sh -c \"printf \%\s'\n' %s >$CDIR/Selection\"" --window-icon=$ICO --list --title="$NAME" --window-icon=$ICO --text "What do you want to install?" --height=500 --width=350 --column="Application" $APPLIST | tr -d '|')
fi
if [[ -z "${APPNAME// }" ]]
then
aexit
fi
setwineprefix
wineverread
if [ -z "$CLI" ]
then
bash /usr/local/share/$NAME/Tools/Framework| yad --progress --title="$NAME" --text="Installation of $APPNAME" --window-icon=$ICO --percentage=0
else
bash /usr/local/share/$NAME/Tools/Framework
fi
}

# Don't create any debug output if we won't see it anyway.
if [ -t 0 ] ; then
export WINEDEBUG=warn+trace+fixme+err
else
export WINEDEBUG=-all
export DXVK_LOG_LEVEL=none
export VKD3D_DEBUG=none
fi

# Set Mesa shader cache to our own folder.
export MESA_SHADER_CACHE_DIR=$CDIR
export MESA_DISK_CACHE_DATABASE=1

# CLI

Install() {
CLI=1
export APPNAME=$1
TODO=101
}

Launch() {
CLI=1
export APPNAME=$1
TODO=100
}

Uninstall() {
CLI=1
export APPNAME=$1
export TODO=99
}

Kill() {
CLI=1
export APPNAME=$1
export TODO=97
}

Winetricks() {
CLI=1
export APPNAME=$1
export TODO=98
}

List() {
CLI=1
List=$1
if [[ $List == *"Library"* ]]; then
cd $LDIR && ls | grep -v README.md | less
fi
if [[ $List == *"Installed"* ]]; then
cd "$GDIR" && ls && cd "$PDIR" && ls | sort
fi
exit
}

"$@"

if [ -z "$(ls -A $GDIR && ls -A $PDIR )" ]; then
MSG="Currently you have no applications installed."
fi

# Initial menu
if [ -z "$CLI" ]
then
APPNAME=$(yad --select-action="/bin/sh -c \"printf \%\s'\n' %s >$CDIR/Selection\"" --buttons-layout=spread --button="Installation:101" --button="Launch:100" --button="Uninstall:99" --button="Winetricks:98" --button="Kill process:97"  --button="Open directory:94" --button="Settings and more:96" --button="Exit:95" --window-icon=$ICO --list --title="$NAME" --window-icon=$ICO --text "Welcome to $NAME! $MSG" --height=350 --column="Application" $APPINST)
TODO=$?
if [ -f "$CDIR/Selection" ]; then
export APPNAME=$(cat $CDIR/Selection)
fi
fi

function checkselection {
if [ -z "$CLI" ]
then
if [ ! -f $CDIR/Selection ];
then
echo "No Selection was made"
aexit
fi
fi
}

if [[ $TODO == *"101"* ]]; then
installdialog
fi

if [[ $TODO == *"100"* ]]; then
checkselection
export TODO=Launcher
setwineprefix
wineverread
if [[ $BackupPrefixRegistry == *"On"* ]]; then
if [ ! -d "$APPDIR/BackupPrefixRegistry" ]; then
mkdir $APPDIR/BackupPrefixRegistry
fi
cp -f $APPDIR/.update-timestamp $APPDIR/BackupPrefixRegistry
cp -f $APPDIR/system.reg $APPDIR/BackupPrefixRegistry
cp -f $APPDIR/user.reg $APPDIR/BackupPrefixRegistry
cp -f $APPDIR/userdef.reg $APPDIR/BackupPrefixRegistry
sync
fi
bash /usr/local/share/$NAME/Tools/Framework
fi

if [[ $TODO == *"99"* ]]; then
checkselection
export TODO=Uninstallation
QT=$(question "Do you really want to uninstall $APPNAME?")
if [[ $QT == *"0"* ]]; then
echo "Starting Uninstallation"
fi
if [[ $QT == *"1"* ]]; then 
echo "Uninstallation has been cancelled"
exec $EXECNAME
fi
setwineprefix
bash /usr/local/share/$NAME/Tools/Framework
fi

if [[ $TODO == *"98"* ]]; then
checkselection
setwineprefix
wineverread
winetricks
fi

if [[ $TODO == *"97"* ]]; then
checkselection
setwineprefix
wineverread
$WINEPATH/wineserver -k
exit
fi

if [[ $TODO == *"94"* ]]; then
checkselection
setwineprefix
xdg-open $WINEPREFIX
fi

if [[ $TODO == *"96"* ]]; then
SAM=$(yad --list --window-icon=$ICO --height=250 --width 250 --title="$NAME - Settings and more" --text "What do you want to do?" --no-headers  --column=Name "Edit configuration file" "Update library" "Patch an executable for LAA" "Support" "Delete and reset everything" | tr -d '|')

if [[ $SAM == *"Edit configuration file"* ]]; then
content=$(yad --text-info --width=1000  --height=500 --filename=$HOME/.config/$NAME.conf --editable --window-icon=$ICO --title "$NAME - $SAM" --text "Close this window if you are done editing.")
[ $? -eq 0 ] && echo "$content" > $HOME/.config/$NAME.conf
fi

if [[ $SAM == *"Update library"* ]]; then
UL=$(question "Updating the library will delete unsubmitted changes, do you want to continue?")
if [[ $UL == *"0"* ]]; then
rm -r -d $LDIR
find $CDIR -iname *.7z -exec rm {} \;
find $CDIR -iname *.zip -exec rm {} \;
find $CDIR -iname *.exe -exec rm {} \;
find $CDIR -iname *.msi -exec rm {} \;
find $CDIR -iname *.rar -exec rm {} \;
library-loader
fi
if [[ $UL == *"1"* ]]; then 
echo "Library update has been cancelled"
fi
fi

if [[ $SAM == *"Patch an executable for LAA"* ]]; then
checkselection
setwineprefix
wineverread
PEXE=$(yad --file --title="$NAME - Select your executable" --window-icon=$ICO)
if [ -z "$PEXE" ]
then
echo "No executable was selected."
aexit
fi
LAA_Patch "$PEXE"
fi

if [[ $SAM == *"Support"* ]]; then
xdg-open https://codeberg.org/Alexander88207/Mizutamari/issues/new
fi

if [[ $SAM == *"Delete and reset everything"* ]]; then
DRQ=$(yad --question --window-icon=$ICO --width 300 --title "$NAME - $SAM" --text "Do you really want to delete and reset everything?"; echo $?)
if [[ $DRQ == *"0"* ]]; then
rm -r -d -f $ProjectPath
rm $HOME/.config/$NAME.conf
if [ -f "$HOME/.local/share/applications/$NAME.desktop" ]; then
rm "$HOME/.local/share/applications/$NAME.desktop"
else 
echo -e "\e[40;38;5;32mNo shortcut was created\e[30;48;5;82m\e[0m"
fi
yad --info --window-icon=$ICO --width=200 --title="$NAME - $OTR" --text="All files of $NAME have been deleted, we hope you had a good time."
exit
fi
fi
fi

if [[ $TODO == *"95"* ]]; then
exit
fi

if [ -f "$CDIR/Selection" ]; then
rm $CDIR/Selection
fi

aexit

#
#
#
#
#
