#!/usr/bin/bash

if [ "$EUID" = 0 ]; then
    clear
    echo "####   Please do not run this script as root!   ####"
    exit 1
fi

export RED='\033[1;91m'
export GREEN='\033[1;92m'
export YELLOW='\033[1;93m'
export BLUE='\033[1;94m'
export END='\033[1;00m'

export SW_GIT_VER="420"
export RUNTIME_GIT_VER="1.0"

SOURCE_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. >/dev/null 2>&1 && pwd )"
export SOURCE_PATH
export START_WINE_PATH="$SOURCE_PATH"

PREFIX="$2"

if [[ -n "$PREFIX" ]]; then
    if [[ -w "$PREFIX" && -d "$PREFIX" ]]; then
        if [[ "$PREFIX" == *"/StartWine" ]]; then
            export START_WINE_PATH="$PREFIX"
        else
            export START_WINE_PATH="$PREFIX/StartWine"
        fi
    else
        echo -e "$RED[ ERROR ] The path does not exist, is not a directory, or is not writable!"
        echo -e "$YELLOW[ NOTE ] Please specify a valid path.$END"
        exit 1
    fi
fi

export SW_SCRIPTS_SOURCE="${SOURCE_PATH}/data/scripts"
export SW_SCRIPTS="${START_WINE_PATH}/data/scripts"

export SW_RUNTIME_BASE="${START_WINE_PATH}/data/runtime/sw_runtime_base"
export SW_RUNTIME="${START_WINE_PATH}/data/runtime/sw_runtime"

export SW_TARGET="${SOURCE_PATH}/data/target"
export SW_TARGET_RELEASE="${SW_TARGET}/release/sw_start"

export SW_START_SOURCE="${SW_SCRIPTS_SOURCE}/sw_start"

export SW_ENV_SOURCE="${SW_SCRIPTS_SOURCE}/env"
export SW_ENV="${SW_SCRIPTS}/env"

export URL_RUNTIME_BASE=(
    "https://huggingface.co/SudoNano/sw_repo/resolve/main/runtime/sw_runtime_base.iso?download=true"
    "https://startwine-launcher.ru/StartWine-data/runtime/sw_runtime_base.iso"
)

export URL_RUNTIME=(
    "https://huggingface.co/SudoNano/sw_repo/resolve/main/runtime/sw_runtime.iso?download=true"
    "https://startwine-launcher.ru/StartWine-data/runtime/sw_runtime.iso"
)

[ -n "$(tty|grep -v 'not a'|grep -Eo 'tty|pts')" ] && \
    export SW_SILENT_DL=1


try_download () {

    if [ ! -n "$(tty|grep -v 'not a'|grep -Eo 'tty|pts')" ]; then
        export NOT_TERM=1
    else
        export NOT_TERM=0
    fi

    is_exist () { command -v "$@" &>/dev/null ; }

    err_no_downloader () {

        error_msg "Downloader not found!"
        exit 1

    }

    check_url_stat_code () {

        if is_exist curl ; then
            curl -sL -o /dev/null -I -w "%{http_code}" "$@" 2>/dev/null
        elif is_exist wget ; then
            wget --no-check-certificate --server-response \
            --spider "$@"|& awk '/^  HTTP/{print$2}'|tail -1
        else
            return 1
        fi

    }

    is_url () {

        [ ! -n "$1" ] && \
            return 1

        if [ -n "$2" ]; then
            [ "$(check_url_stat_code "$1")" == "$2" ]
        else
            [ "$(check_url_stat_code "$1")" == "200" ]
        fi

    }

    yn_case () {

        while true ; do
            read -p "$(echo -e "${RED}$1 ${GREEN}(y/n) ${BLUE}> $END")" yn
            case $yn in
                [Yy] ) return 0 ;;
                [Nn] ) return 1 ;;
            esac
        done

    }

    error_msg () {

        echo -e "${RED}[ ERROR ][$(date +"%Y.%m.%d %T")]: $@ $END"
        if [ "$NOT_TERM" == 1 ]; then
            notify-send -a 'StartWine Error' "$@" 2>/dev/null &
        fi

    }

    rm_fail_dl () {

        [ -f "$FILEDIR/$FILENAME" ] && \
            rm -rf "$FILEDIR/$FILENAME" \
            "$FILEDIR/$FILENAME"*.aria2

    }

    dl_ret () {

        if [ "$1" != 0 ]; then
            rm_fail_dl
            dl_repeat && try_download "$URL" "$FILEDIR/$FILENAME" || return 1
        else
            return 0
        fi

    }

    dl_repeat () {

        DL_REP_TITLE="Download interrupted!"
        DL_REP_TEXT="Failed to download: $FILENAME from $(echo "$URL"|awk -F/ '{print$3"/"$4}') \nWould you like to repeat it?"

        if [ "$NOT_TERM" != 1 ]; then
            yn_case "$DL_REP_TEXT"||return 1
        elif is_exist yad ; then
            yad --image="dialog-error" --button="CANCEL:1" --center \
            --button="REPEAT:0" --title="$DL_REP_TITLE" \
            --text="$DL_REP_TEXT" --on-top --fixed
        elif is_exist zenity ; then
            zenity --question --title="$DL_REP_TITLE" --no-wrap \
            --text="$DL_REP_TEXT"
        else
            return 1
        fi

    }

    if [ -n "$1" ]; then
        URL="$1"

        if [ -n "$2" ]; then
            if [ -d "$2" ]; then
                FILEDIR="$2"
                FILENAME="$(basename "$1")"
            else
                FILEDIR="$(dirname "$2")"
                FILENAME="$(basename "$2")"
            fi
        else
            FILEDIR="."
            FILENAME="$(basename "$1")"
        fi

        if is_url "$URL" ; then
            WGET_ARGS=(--no-check-certificate --content-disposition -t 3 -T 5 -w 0.5 "$URL" -O "$FILEDIR/$FILENAME")
            [ ! -d "$FILEDIR" ] && \
                mkdir -p "$FILEDIR"

            if [ "$NOT_TERM" == 1 ] && (is_exist yad||is_exist zenity) ; then
                set -o pipefail

                dl_progress () {

                    [[ "$URL" =~ '&key=' ]] && \
                        local URL="$(echo "$URL"|sed "s|\&key=.*||g")"
                    [[ "$URL" =~ '&' && ! "$URL" =~ '&amp;' ]] && \
                        local URL="$(echo "$URL"|sed "s|\&|\&amp;|g")"
                    if is_exist yad ; then
                        yad --progress --percentage=0 --text="Download:\t$FILENAME\n$URL" \
                        --auto-close --no-escape --selectable-labels --auto-kill \
                        --center --on-top --fixed --no-buttons --undecorated --skip-taskbar
                    elif is_exist zenity ; then
                        zenity --progress --text="Connecting to $URL" --width=650 --height=40 \
                        --auto-close --no-cancel --title="Download: $FILENAME"
                    else
                        return 1
                    fi

                }

                dl_progress_pulsate () {

                    local ret=1
                    [[ "$URL" =~ '&key=' ]] && \
                        local URL="$(echo "$URL"|sed "s|\&key=.*||g")"
                    [[ "$URL" =~ '&' && ! "$URL" =~ '&amp;' ]] && \
                        local URL="$(echo "$URL"|sed "s|\&|\&amp;|g")"

                    if is_exist yad ; then
                        local yad_args=(
                            --progress --pulsate --text="Download:\t$FILENAME\n$URL"
                            --width=650 --height=40 --undecorated --skip-taskbar
                            --no-buttons --text-align center --auto-close --auto-kill
                            --center --fixed --on-top --no-escape --selectable-labels
                        )
                        "$@" &
                        local exec_pid="$!"

                        if [[ -n "$exec_pid" && -d "/proc/$exec_pid" ]]; then
                            (while [ -d "/proc/$exec_pid" ]
                                do echo -e "#\n" ; sleep 0.1 2>/dev/null
                            done)|yad "${yad_args[@]}" &>/dev/null &
                            local yad_pid="$!"
                            wait "$exec_pid" &>/dev/null
                            ret="$?"
                            kill "$yad_pid" &>/dev/null
                        fi

                    elif is_exist zenity ; then
                        "$@"|zenity --progress --pulsate --text="$URL" --width=650 --height=40 \
                        --auto-close --no-cancel --title="Download: $FILENAME"
                        ret="$?"
                    fi

                    return "$ret"

                }

                if is_exist aria2c ; then
                    aria2c --no-conf -R -x 13 -s 13 --allow-overwrite --summary-interval=1 -o \
                    "$FILENAME" -d "$FILEDIR" "$URL"|grep --line-buffered 'ETA'|\
                    sed -u 's|(.*)| &|g;s|(||g;s|)||g;s|\[||g;s|\]||g'|\
                    awk '{print$3"\n#Downloading at "$3,$2,$5,$6;system("")}'|\
                    dl_progress
                elif is_exist curl ; then
                    curl -R --progress-bar --insecure --fail -L "$URL" -o \
                    "$FILEDIR/$FILENAME" |& tr '\r' '\n'|sed '0,/100/{/100/d;}'|\
                    sed -ur 's|[# ]+||g;s|.*=.*||g;s|.*|#Downloading at &\n&|g'|\
                    dl_progress
                elif is_exist wget2 ; then
                    dl_progress_pulsate wget2 "${WGET_ARGS[@]}"
                elif is_exist wget ; then
                    wget "${WGET_ARGS[@]}"|& tr '\r' '\n'|\
                    sed -u 's/.* \([0-9]\+%\)\ \+\([0-9,.]\+.\) \(.*\)/\1\n#Downloading at \1\ ETA: \3/; s/^20[0-9][0-9].*/#Done./'|\
                    dl_progress
                else
                    err_no_downloader
                fi

                dl_ret "${PIPESTATUS[0]}"||return 1
            else
                if is_exist aria2c ; then
                    aria2c --no-conf -R -x 13 -s 13 --allow-overwrite -d "$FILEDIR" -o "$FILENAME" "$URL"
                elif is_exist curl ; then
                    curl -R --progress-bar --insecure --fail -L "$URL" -o "$FILEDIR/$FILENAME"
                elif is_exist wget2 ; then
                    wget2 -q --force-progress "${WGET_ARGS[@]}"
                elif is_exist wget ; then
                    wget -q --show-progress "${WGET_ARGS[@]}"
                else
                    err_no_downloader
                fi

                dl_ret "$?"||return 1
            fi
        else
            error_msg "$FILENAME not found in $(echo "$URL"|awk -F/ '{print$3"/"$4}')"
            return 1
        fi
    else
        error_msg "Specify download URL!"
        return 1
    fi

}

clean_local () {

    [ -L "$HOME/.local/bin/sw" ] && \
        rm "$HOME/.local/bin/sw" && \
            echo -e "${RED}[ Remove ] $HOME/.local/bin/sw${END}"

    [ -L "$HOME/.local/bin/sw_uninstaller" ] && \
        rm "$HOME/.local/bin/sw_uninstaller" && \
            echo -e "${RED}[ Remove ] $HOME/.local/bin/sw_uninstaller${END}"

    [ -f "$HOME/.local/share/applications/StartWine.desktop" ] && \
        rm -rf "$HOME/.local/share/applications/StartWine.desktop" && \
            echo -e "${RED}[ Remove ] $HOME/.local/share/applications/StartWine.desktop${END}"

    [ -f "$HOME/.local/share/applications/ru.launcher.StartWine.desktop" ] && \
        rm -rf "$HOME/.local/share/applications/ru.launcher.StartWine.desktop" && \
            echo -e "${RED}[ Remove ] $HOME/.local/share/applications/ru.launcher.StartWine.desktop${END}"

    [ -f "$HOME/.local/share/applications/StartWineShell.desktop" ] && \
        rm -rf "$HOME/.local/share/applications/StartWineShell.desktop" && \
            echo -e "${RED}[ Remove ] $HOME/.local/share/applications/StartWineShell.desktop${END}"

    [ -f "${HOME}/.cache/sw_fm/appid.json" ] && \
        rm -rf "${HOME}/.cache/sw_fm/appid.json" && \
            echo -e "${RED}[ Remove ] ${HOME}/.cache/sw_fm/appid.json${END}"

}

clean_download () {

    echo -e "${YELLOW}[ INFO ] Cleaning downloaded files...${END}"

    [ -f "${SW_SCRIPTS_SOURCE}/winetricks" ] && \
        rm -rf "${SW_SCRIPTS_SOURCE}/winetricks" && \
            echo -e "${RED}[ Remove ] ${SW_SCRIPTS_SOURCE}/winetricks${END}"

    [ -L "${SOURCE_PATH}/data/runtime/sw" ] && \
        rm "${SOURCE_PATH}/data/runtime/sw" && \
            echo -e "${RED}[ Remove ] ${SOURCE_PATH}/data/runtime/sw${END}"

    for dir in pfx_backup runtime tmp tools wine; do
        [ -d "${SOURCE_PATH}/data/${dir}" ] && \
            rm -rf "${SOURCE_PATH}/data/${dir}" && \
                echo -e "${RED}[ Remove ] ${SOURCE_PATH}/data/${dir}${END}"
    done
}

clean_cache () {

    echo -e "${YELLOW}[ INFO ] Cleaning the build cache...${END}"

    [ -d "${SW_SCRIPTS_SOURCE}/__pycache__" ] && \
        rm -rf "${SW_SCRIPTS_SOURCE}/__pycache__" && \
            echo -e "${RED}[ Remove ] ${SW_SCRIPTS_SOURCE}/__pycache__${END}"

    [ -f "${SW_SCRIPTS_SOURCE}/winetricks" ] && \
        rm -rf "${SW_SCRIPTS_SOURCE}/winetricks" && \
            echo -e "${RED}[ Remove ] ${SW_SCRIPTS_SOURCE}/winetricks${END}"

    [ -f "${SOURCE_PATH}/data/Cargo.lock" ] && \
        rm -rf "${SOURCE_PATH}/data/Cargo.lock" && \
            echo -e "${RED}[ Remove ] ${SOURCE_PATH}/data/Cargo.lock${END}"

    [ -d "${SW_TARGET}" ] && \
        rm -rf "${SW_TARGET}" && \
            echo -e "${RED}[ Remove ] ${SW_TARGET}${END}"

}

clean_build () {

    echo -e "${YELLOW}[ INFO ] Cleaning the build files...${END}"

    clean_cache

    [ -f "${SW_START_SOURCE}" ] && \
        rm -rf "${SW_START_SOURCE}" && \
            echo -e "${RED}[ Remove ] ${SW_START_SOURCE}${END}"

    [ -d "${SW_ENV_SOURCE}" ] && \
        rm -rf "${SW_ENV_SOURCE}" && \
            echo -e "${RED}[ Remove ] ${SW_ENV_SOURCE}${END}"

}

clean_img () {

    [ -d "${SOURCE_PATH}/data/img/sw_themes/css/custom" ] && \
        rm -rf "${SOURCE_PATH}/data/img/sw_themes/css/custom" && \
            echo -e "${RED}[ Remove ] ${SOURCE_PATH}/data/img/sw_themes/css/custom${END}"

    for dir in app_icons epic_icons gog_icons; do
        [ -d "${SOURCE_PATH}/data/img/$dir" ] && \
            rm -rf "${SOURCE_PATH}/data/img/$dir" && \
                echo -e "${RED}[ Remove ] ${dir}${END}"
    done

}

clean_app_config () {

    for file in "${SOURCE_PATH}/data/app_config/"*; do
        [ -f "${file}" ] && \
            rm -rf "${file}" && \
                echo -e "${RED}[ Remove ] ${file}${END}"
    done

}

clean_all () {

    echo -e "${YELLOW}[ INFO ] Cleaning build directories...${END}"

    clean_local
    clean_build
    clean_img
    clean_app_config

    for dir in app_saves pfx pfx_backup runtime tmp tools wine; do
        [ -d "${SOURCE_PATH}/data/${dir}" ] && \
            rm -rf "${SOURCE_PATH}/data/${dir}" && \
                echo -e "${RED}[ Remove ] ${dir}${END}"
    done

}

print_note () {

    echo -e "${YELLOW}[ NOTE ] This option is not recommended for several reasons:
        ${GREEN}
        - Requires installing a significant list of dependencies.
        - Running Windows applications using Wine in a non-isolated environment potentially poses a security risk.
        - Using an isolated runtime environment significantly increases the likelihood of a successful launch.
        - You will need to install the dependencies for your Linux distribution manually. ( See the indicative list below )
        - Inconsistencies in library versions across different distributions may cause launch issues.
        Howerver the choice is always yours. May the Force be with you!
        ${END}"

}

print_dep () {

    echo -e "${YELLOW}[ NOTE ] Make sure the following libraries are installed:"
    echo -e "
    ${GREEN}[ INFO ] StartWine build dependencies:
        - python3 >= 3.13
        - cargo >= 1.88
        - rustup
        - gettext
        - cairo
        - glib
        - gio
        - gobject
        - gdk-pixbuf
        - gdk4
        - pango
        - graphene
        - gsk4
        - gtk4
        - libraw
    ${END}"

}

print_runtime_dep () {

    echo -e "${YELLOW}[ NOTE ] The list of library packages below is approximate,
    as it is not feasible to maintain it for every specific distribution.
    But this will give you a good starting point.${END}"
    echo -e "
    ${GREEN}[ INFO ] StartWine runtime and wine dependencies:
        - dbus zstd sed grep pgrep libnotify curl
        - gettext fontconfig wqy-microhei inih cmake
        - wl-clipboard xclip
        - fuse3 squashfs-tools
        - diffoscope b3sum rclone rsync binwalk innoextract
        - pipewire gstreamer-pipewire
        - gstreamer gst-plugins-*(base, good, bad, ugly) gstreamer-vaapi ( 64, 32 bit libs )
        - ffmpeg
        - gtk4 vte3-gtk4 gtk4-layer-shell libwebkit60
        - libunwind libunwind-32bit samba smbclient
        - wayland libseat libinput xwayland libdisplay-info
        - mesa mesa-vaapi mesa-vulkan vulkan-loader libspa-vulkan
        - gvfs gvfs-afc gvfs-afp gvfs-cdda gvfs-gphoto2 gvfs-mtp gvfs-smb
        - xdg-user-dirs xdg-utils xdg-dbus-proxy
        - vkBasalt vkBasalt-32bit
        - wine dependencies ( 64, 32 bit libs )
    ${END}"

}

print_err_note () {

    echo -e "${RED}[ ERROR ] Failed to build sw_start!${END}" &&
    print_dep

}

build_runtime () {

    if [ ! -f "${SW_RUNTIME}" ]; then
        if [ ! -f "${SW_RUNTIME_BASE}" ]; then
            echo -e "${YELLOW}[ INFO ] Download base runtime...${END}"
            try_download "${URL_RUNTIME_BASE[0]}" "${SW_RUNTIME_BASE}" \
            || try_download "${URL_RUNTIME_BASE[1]}" "${SW_RUNTIME_BASE}" &&
            chmod +x "${SW_RUNTIME_BASE}"
        fi

        if [ -f "${SW_RUNTIME_BASE}" ]; then
            echo -e "${YELLOW}[ INFO ] Building runtime...${END}"
            cd "${START_WINE_PATH}/data/runtime"
            RIM_OVERFS_MODE=1 ./sw_runtime_base sw-runtime-build
            rm -fr "${SW_RUNTIME_BASE}"
            cd "${SOURCE_PATH}/data"
        fi
    fi

}

build_rust () {

    echo -e "${YELLOW}[ INFO ] Building rust source...${END}"

    if [ ! command -v cargo &> /dev/null ]; then
        curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
        rustup update
    fi

    [ -f "$SW_START_SOURCE" ] && \
        rm -rf "$SW_START_SOURCE"

    cargo build --release || print_err_note

    if [ -f "$SW_TARGET_RELEASE" ]; then
        cp -f "$SW_TARGET_RELEASE" "$SW_START_SOURCE"
    elif [ -d "$SW_TARGET" ]; then
        cargo clean
        exit 1
    else
        echo -e "${RED}[ ERROR ] sw_start missing in the target directory!${END}"
        exit 1
    fi

}

build_python () {

    echo -e "${YELLOW}[ INFO ] Building Python environment...${END}"

    if [ ! -f "${SW_RUNTIME}" ]; then
        export CMD=
    else
        export CMD="${SW_RUNTIME}"
    fi

    if command -v $CMD python3 &> /dev/null; then
        VERSION=$($CMD python3 -V 2>&1 | cut -d ' ' -f 2 | tr -d [:alpha:][:punct:] | tail -n1)
        echo -e "${BLUE}[ INFO ] $($CMD python3 -V) ${END}"

        if [[ "$VERSION" < "313" ]]; then
            echo -e "${RED}[ WARN ] Python version lower 3.13 ${END}"
            return 1
        fi

        if [ -f "$SW_START_SOURCE" ]; then
            $CMD "$SW_START_SOURCE" --update
            source "${SW_ENV_SOURCE}/bin/activate"
        else
            $CMD python3 -m venv "${SW_ENV_SOURCE}"
            source "${SW_ENV_SOURCE}/bin/activate"
            $CMD pip install --upgrade pip || return 1
            $CMD pip install -r "${SW_SCRIPTS_SOURCE}/requirements.txt" || return 1
        fi
    else
        echo -e "${RED}[ WARNING ] Python3 not installed! Skipping...${END}"
    fi

}

check_dirs () {

    [ ! -d "$HOME/.config" ] && \
        mkdir -p "$HOME/.config"

    [ ! -d "$HOME/.local/bin" ] && \
        mkdir -p "$HOME/.local/bin"

    [ ! -d "$HOME/.local/share/applications" ] && \
        mkdir -p "$HOME/.local/share/applications"

    [ ! -d "${START_WINE_PATH}/data/runtime" ] && \
        mkdir -p "${START_WINE_PATH}/data/runtime"

    [ ! -d "${START_WINE_PATH}/data/tmp" ] && \
        mkdir -p "${START_WINE_PATH}/data/tmp"

}

download_base () {

    check_dirs

    if [ ! -f "${SW_RUNTIME_BASE}" ]; then
        echo -e "${YELLOW}[ INFO ] Download base runtime...${END}"
        try_download "${URL_RUNTIME_BASE[0]}" "${SW_RUNTIME_BASE}" \
        || try_download "${URL_RUNTIME_BASE[1]}" "${SW_RUNTIME_BASE}" &&
        chmod +x "${SW_RUNTIME_BASE}"
        echo -e "${GREEN}[ INFO ] Downloaded to ${SW_RUNTIME_BASE} complete.${END}"
    fi

}

download_runtime () {

    check_dirs

    if [ ! -f "${SW_RUNTIME}" ]; then
        echo -e "${YELLOW}[ INFO ] Download runtime...${END}"
        try_download "${URL_RUNTIME[0]}" "${SW_RUNTIME}" \
        || try_download "${URL_RUNTIME[1]}" "${SW_RUNTIME}" &&
        chmod +x "${SW_RUNTIME}"
        echo -e "${GREEN}[ INFO ] Downloaded to ${SW_RUNTIME} complete.${END}"
    fi

}

copy_source () {

    if [ "${START_WINE_PATH}" != "${SOURCE_PATH}" ]; then
        echo "${YELLOW}[ INFO ]Copy source to target...${END}"
        for dir in app_config app_patches img scripts; do
            cp -r "${SOURCE_PATH}/data/${dir}" "${START_WINE_PATH}/data"
        done
    fi

}

create_links () {

    [ ! -L "$HOME/.local/bin/sw" ] && \
        ln -sfr "${SW_RUNTIME}" "$HOME/.local/bin/sw"

    [ ! -L "${START_WINE_PATH}/data/runtime/sw" ] && \
        ln -sfr "${SW_RUNTIME}" "${START_WINE_PATH}/data/runtime/sw"

    [ ! -L "$HOME/.local/bin/sw_uninstaller" ] && \
        ln -sfr "${SW_SCRIPTS}/sw_uninstaller" "$HOME/.local/bin/sw_uninstaller"

}

build_all () {

    echo -e "${GREEN}[ INFO ] Build the release with runtime container.${END}"
    print_dep

    read -p "Press Enter to continue or N to cancel: " value

    if [ "$value" != "" ]; then
        echo "exit..."
        exit 0
    fi

    clean_build
    check_dirs
    build_runtime
    build_release

}

build_naked () {

    echo -e "${GREEN}[ INFO ] Building naked release.${END}"
    print_note
    print_dep
    print_runtime_dep

    read -p "Press Enter to continue or N to cancel: " value

    if [ "$value" != "" ]; then
        echo "exit..."
        exit 0
    fi

    clean_build
    check_dirs
    build_rust
    build_python
    copy_source
    create_links

    echo "${SW_GIT_VER}" > "${SW_SCRIPTS}/version"
    echo "${RUNTIME_GIT_VER}" > "${START_WINE_PATH}/data/runtime/version"
    echo "${START_WINE_PATH}" > "$HOME/.config/swrc"

    "${SW_SCRIPTS}/sw_runlib"

    clean_cache

    echo -e "${GREEN}[ INFO ] Building completed successfully.${END}"
    exit 0

}

build_release () {

    echo -e "${GREEN}[ INFO ] Building release.${END}"

    clean_build
    check_dirs
    download_runtime
    build_rust
    build_python
    copy_source

    if [ -f "${SW_RUNTIME}" ]; then
        create_links
        "${SW_RUNTIME}" cp -f "/usr/bin/ssrv" "${START_WINE_PATH}/data/runtime/ssrv"

        echo "${SW_GIT_VER}" > "${SW_SCRIPTS}/version"
        echo "${RUNTIME_GIT_VER}" > "${START_WINE_PATH}/data/runtime/version"
        echo "${START_WINE_PATH}" > "$HOME/.config/swrc"

        "${SW_RUNTIME}" "${SW_SCRIPTS}/sw_runlib"

        clean_cache

        echo -e "${GREEN}[ INFO ] Building completed successfully.${END}"
        exit 0
    else
        echo -e "${RED}[ ERROR ] $SW_RUNTIME not exists!${END}"
    fi

}

helper () {

    echo -e "${BLUE}-----------------------------------------------------"
    echo -e "${YELLOW}USAGE:
    ${GREEN}[./build] [COMMAND] [PATH]"
    echo -e "${BLUE}-----------------------------------------------------"
    echo -e "${YELLOW}DEFAULT PATH: ${SOURCE_PATH}"
    echo -e "${BLUE}-----------------------------------------------------"
    echo -e "${YELLOW}COMMANDS:
    ${BLUE}all                   ${GREEN}Build all ( release source and runtime ).
    ${BLUE}release               ${GREEN}Build the release and download the latest runtime.
    ${BLUE}naked                 ${GREEN}Build the release without runtime. ( not recommended )
    ${BLUE}rust                  ${GREEN}Build only the rust source.
    ${BLUE}python                ${GREEN}Build only the python source.
    ${BLUE}runtime               ${GREEN}Build only the runtime.
    ${BLUE}download-base         ${GREEN}Download the minimal base runtime.
    ${BLUE}download-runtime      ${GREEN}Download the latest release runtime.
    ${BLUE}clean                 ${GREEN}Remove build files.
    ${BLUE}clean-download        ${GREEN}Remove downloaded files.
    ${BLUE}clean-all             ${GREEN}Remove all build and downloaded files.
    ${BLUE}help                  ${GREEN}Print help.
    ${BLUE}-----------------------------------------------------${END}"

}

commandline=${1:-help}

case $commandline in
    all                 ) build_all;;
    release             ) build_release;;
    naked               ) build_naked;;
    rust                ) build_rust;;
    python              ) build_python;;
    runtime             ) build_runtime;;
    download-base       ) download_base;;
    download-runtime    ) download_runtime;;
    clean               ) clean_build;;
    clean-download      ) clean_download;;
    clean-all           ) clean_all;;
    help                ) helper;;
    *                   ) helper;;
esac

