#!/bin/sh
#
# SPDX-License-Identifier: MIT
#

if [ ! -z "$PM_FUNCS_VERSION" ]; then
    return
fi

# So we can check the version, eg: [ "${PM_FUNCS_VERSION:-0}" -ge 4 ]
# Bump it whenever ports get something new to use:
#   3: the original funcs.txt
#   4: pm_message / pm_show_error take portmsg options (--title, --timeout, ...),
#      pm_message_close
#   5: PM_LIBRARY_PATH, PortMaster's libs.<arch> (also at the end of LD_LIBRARY_PATH)
export PM_FUNCS_VERSION=5

export PM_SCRIPTNAME="$(basename "${PM_SCRIPTNAME:-$0}")"
export PM_PORTNAME="${PM_PORTNAME:-${PM_SCRIPTNAME%.sh}}"
export PM_VERSION="$(cat "$controlfolder/version")"
export PM_RESOURCE_DIR="$controlfolder/resources"
export PM_CAN_MOUNT="${PM_CAN_MOUNT:-Y}"

# muOS stuff.
if [[ "$CFW_NAME" == "muOS" ]]; then
    export LD_LIBRARY_PATH="/opt/muos/extra/lib:$LD_LIBRARY_PATH"
fi

# Libraries ports often need that some CFWs don't have (eg: libtheora, which the love
# runtime is built against), in $controlfolder/libs.<arch>. They go after the system's
# own, so they only fill in what's missing; a port that wants them first can use
#   export LD_LIBRARY_PATH="$PM_LIBRARY_PATH:$LD_LIBRARY_PATH"
# aarch64 devices get armhf's too, for 32-bit ports: the loader skips libraries of the
# other architecture, so this works without knowing PORT_32BIT (ports set it after
# sourcing control.txt). When it's already set, armhf's come first.
if [ "$DEVICE_ARCH" = "aarch64" ]; then
    if [ "${PORT_32BIT:-N}" = "Y" ]; then
        PM_LIBRARY_PATH="$controlfolder/libs.armhf:$controlfolder/libs.aarch64"
    else
        PM_LIBRARY_PATH="$controlfolder/libs.aarch64:$controlfolder/libs.armhf"
    fi
else
    PM_LIBRARY_PATH="$controlfolder/libs.${DEVICE_ARCH}"
fi
export PM_LIBRARY_PATH
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH:}$PM_LIBRARY_PATH"

source "$controlfolder/PortMasterDialog.txt"

# Extract the latest NotoSans.tar.xz
if [ -f "$controlfolder/pylibs/resources/NotoSans.tar.xz" ]; then
    # TODO: make sure this works on all CFW.
    $ESUDO tar -C "$controlfolder/pylibs/resources" -xf "$controlfolder/pylibs/resources/NotoSans.tar.xz"

    if [ -f "$controlfolder/pylibs/resources/NotoSansJP-Regular.ttf" ]; then
        $ESUDO rm -f "$controlfolder/pylibs/resources/NotoSans.tar.xz"
    fi
fi

if [ -f "$PM_RESOURCE_DIR/do_init" ]; then
    $ESUDO cp -f "$controlfolder"/pylibs/resources/*.ttf "$PM_RESOURCE_DIR/"

    $ESUDO rm -f "$PM_RESOURCE_DIR/do_init"
fi


bind_directories() {
    # Usage: bind_directories ~/.config/StardewValley $GAMEDIR/savedata
    #
    # Reason: some platforms (batocera) use exfat for the home directory, so we can't use symbolic links
    # We then instead use bind mount, however retrodeck cannot bind mount because it does not run in root.
    #
    if [ "$PM_CAN_MOUNT" = "Y" ]; then
        [[ -L "$1" ]] && rm -f "$1" && echo "removed previous symlink $1"
        # Ensure the directory exists before attempting the bind mount
        if [ -d "$2" ]; then
            mkdir -p "$1"
            $ESUDO umount "$1"
            $ESUDO mount --bind "$2" "$1" && echo "successful bind mount from $2 to $1"
        else
            echo "no directory found at $2"
        fi
    else
        # RetroDECK cant use bind mount without root.
        rm -f "$1"
        ln -sfv "$2" "$1"
    fi
}

bind_files() {
    # Usage: bind_files ~/.config_file $GAMEDIR/conf/.config_file
    #
    # Reason: some platforms (batocera) use exfat for the home directory, so we can't use symbolic links
    # We then instead use bind mount, however retrodeck cannot bind mount because it does not run in root.
    #
    if [ "$PM_CAN_MOUNT" = "Y" ]; then
        [[ -L "$1" ]] && rm -f "$1" && echo "removed previous symlink $1"
        # Ensure the file exists before attempting the bind mount
        if [ -f "$2" ]; then
            touch "$1"
            $ESUDO umount "$1"
            $ESUDO mount --bind "$2" "$1" && echo "successful bind mount from $2 to $1"
        else
            echo "no file found at $2"
        fi
    else
        # RetroDECK cant use bind mount without root.
        rm -f "$1"
        ln -sfv "$2" "$1"
    fi
}

pm_begin_splash() {
    # Does nothing, noone ever used it, blame ImCoKeMaN
    printf ""
}


# portmsg draws pm_message/pm_show_error, pugwash is the fallback when it is missing.
PM_MSG_BIN="$controlfolder/portmsg.${DEVICE_ARCH}"
PM_MSG_PID=""

pm_message_close() {
    # Removes the current portmsg message right away.
    if [ -n "$PM_MSG_PID" ]; then
        kill "$PM_MSG_PID" 2> /dev/null
        wait "$PM_MSG_PID" 2> /dev/null
        PM_MSG_PID=""
    fi
}


pm_show_error() {
    # Usage: pm_show_error "Message here."
    # Message first, then any portmsg options, e.g. --title "Title". Older PortMaster versions only show the message.
    if [ -x "$PM_MSG_BIN" ]; then
        if [ "${1#--}" = "$1" ]; then
            local text="$1"
            shift
            set -- --text "$text" "$@"
        fi
        pm_message_close
        $ESUDO env $SAVE_CLEAN_ENV LD_LIBRARY_PATH="$SAVE_LD_LIBRARY_PATH" \
            SDL_GAMECONTROLLERCONFIG="${SDL_GAMECONTROLLERCONFIG:-$sdl_controllerconfig}" \
            "$PM_MSG_BIN" "$@"
        return
    fi

    if [ ! -e "$PM_PIPE" ]; then
        PortMasterDialogInit "no-harbour"
        PortMasterDialog "messages_begin"
    fi

    echo "$1"

    PortMasterDialog "message_box" "$1"
}


pm_end_splash() {
    # You get nothing!
    printf ""
}


pm_message_end() {
    if [ -n "$PM_MSG_PID" ]; then
        sleep 3
        pm_message_close
    fi

    if [ -e "$PM_PIPE" ]; then
        sleep 3
        PortMasterDialogExit
    fi
}

trap pm_message_end EXIT

pm_message() {
    echo "$1" # Moved here

    # Skip initing the message and only print to avoid splashing a blank disappearing message
    if [ "$1" = "Patching process already completed. Skipping." ]; then
        return
    fi

    # Usage: pm_message "Some message here."
    # Message first, then any portmsg options, e.g. --title "Title". Older PortMaster versions only show the message.
    # Stays up without a close button until the next message, pm_platform_helper or the end of the script (or --timeout).
    if [ -x "$PM_MSG_BIN" ]; then
        if [ "${1#--}" = "$1" ]; then
            local text="$1"
            shift
            set -- --text "$text" "$@"
        fi
        local mode="--wait"
        case " $* " in *" --timeout "*) mode="" ;; esac
        pm_message_close
        $ESUDO env $SAVE_CLEAN_ENV LD_LIBRARY_PATH="$SAVE_LD_LIBRARY_PATH" \
            SDL_GAMECONTROLLERCONFIG="${SDL_GAMECONTROLLERCONFIG:-$sdl_controllerconfig}" \
            "$PM_MSG_BIN" $mode --type info "$@" &
        PM_MSG_PID=$!
        return
    fi

    if [ ! -e "$PM_PIPE" ]; then
        PortMasterDialogInit "no-harbour"
        PortMasterDialog "messages_begin"
    fi

    PortMasterDialog "message" "$1"
}

pm_gptokeyb_finish() {
    $ESUDO pkill -9 -f gptokeyb
    $ESUDO pkill -9 -f gptokeyb2
}


pm_finish() {
    pm_gptokeyb_finish
    pm_message_end

    $ESUDO systemctl restart oga_events 2> /dev/null &

    if [ ! -z "$(echo "$CUR_TTY" | grep -e '^/dev/tty')" ]; then
        printf "\033c" > "$CUR_TTY"
    fi
}

pm_platform_helper() {
    pm_message_close

    if [ -e "$PM_PIPE" ]; then
        PortMasterDialogExit
    fi

    # DO SOMETHING HERE
    printf ""
}
