#!/bin/bash

# Function to comment/uncomment lines in internal/player.go
function toggle_winio_import() {
    local action="$1"
    local file="internal/player.go"
    
    if [ "$action" == "comment" ]; then
        # Comment out the go-winio import line
        sed -i 's|^\(\s*"github.com/Microsoft/go-winio"\)|// \1|' "$file"
        # Comment out the usage of winio.DialPipe
        sed -i 's|^\(.*conn, err = winio.DialPipe.*\)|// \1|' "$file"
    elif [ "$action" == "uncomment" ]; then
        # Uncomment the go-winio import line
        sed -i 's|// \(\s*"github.com/Microsoft/go-winio"\)|\1|' "$file"
        # Uncomment the usage of winio.DialPipe
        sed -i 's|^// \(.*conn, err = winio.DialPipe.*\)|\1|' "$file"
    fi
}


# Ask for version number
read -p "Enter the version number: " version
release_folder="releases/curd-$version"
windows_folder="$release_folder/windows"
linux_folder="$release_folder/linux"
installer_script="Build/curd-windows-build.iss"

# Ensure required directories exist
mkdir -p "$windows_folder" "$linux_folder"

# Update version in the installer script
sed -i "s/^AppVersion=.*/AppVersion=$version/" "$installer_script"

# Update Source paths in the installer script
sed -i "s|Source: \".*curd.exe\"|Source: \"Z:$windows_folder/curd.exe\"|" "$installer_script"
# sed -i "s|Source: \".*mpv.exe\"|Source: \"Z:$windows_folder/mpv.exe\"|" "$installer_script"

# Comment out winio-related lines for Linux build
echo "Commenting out go-winio lines for Linux build..."
toggle_winio_import "comment"

# Build Linux binary
echo "Building Linux binary..."
bash Build/buildlinux

# Move the Linux binary to the release folder
if [ -f "curd" ]; then
    mv curd "$linux_folder/"
else
    echo "Linux build failed. Please check Build/buildlinux."
    exit 1
fi

# Uncomment winio-related lines after Linux build
echo "Uncommenting go-winio lines..."
toggle_winio_import "uncomment"

# Build Windows binary
echo "Building Windows binary..."
bash Build/buildwindows

# Move the Windows binary to the release folder
if [ -f "curd.exe" ]; then
    mv curd.exe "$windows_folder/"
else
    echo "Windows build failed. Please check Build/buildwindows."
    exit 1
fi

# # Copy mpv.exe to the Windows release folder
# if [ -f "Build/mpv.exe" ]; then
#     cp "Build/mpv.exe" "$windows_folder/"
# else
#     echo "mpv.exe not found. Skipping copy."
# fi

# Create Windows installer with Inno Setup
echo "Creating Windows installer..."
wine "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" "$installer_script"

# Move installer to the release folder
installer_output="Build/Output/CurdInstaller.exe"  # Replace with actual output location if different
if [ -f "$installer_output" ]; then
    mv "$installer_output" "$windows_folder/CurdInstaller-v$version.exe"
else
    echo "Installer creation failed. Please check Inno Setup script output."
fi

echo "Release build completed in $release_folder."
