#!/bin/bash
ZIP_PATH=$1
TARGET_DIR=$2
PROCESS_NAME="GameCore.Master"

sleep 3

# Determine service name based on zip/target
SERVICE_NAME=""
if [[ "$ZIP_PATH" == *"Master"* ]]; then
    SERVICE_NAME="gamecore-master"
elif [[ "$ZIP_PATH" == *"Node"* ]]; then
    SERVICE_NAME="gamecore-node"
fi

if [ ! -z "$SERVICE_NAME" ]; then
    echo "Stopping service $SERVICE_NAME..."
    sudo systemctl stop $SERVICE_NAME
else
    # Fallback to kill if not standard naming
    pkill -f $PROCESS_NAME
fi

# Unzip
unzip -o $ZIP_PATH -d $TARGET_DIR

# Fix permissions
chmod +x $TARGET_DIR/GameCore.Master
chmod +x $TARGET_DIR/GameCore.Node
chown -R gamecore:gamecore $TARGET_DIR

if [ ! -z "$SERVICE_NAME" ]; then
    echo "Starting service $SERVICE_NAME..."
    sudo systemctl start $SERVICE_NAME
else
    # Fallback start
    if [ -f "$TARGET_DIR/GameCore.Master" ]; then
        nohup $TARGET_DIR/GameCore.Master > /dev/null 2>&1 &
    elif [ -f "$TARGET_DIR/GameCore.Node" ]; then
        nohup $TARGET_DIR/GameCore.Node > /dev/null 2>&1 &
    fi
fi

# Cleanup
rm $ZIP_PATH
