#!/bin/sh

# Set the base download URL
BASE_DOWNLOAD_URL="https://so.pingflash.com/release/so"

# Determine the architecture and OS
ARCH=$(uname -m)
OS=$(uname)

case "$ARCH" in
    x86_64)
        ARCH_TYPE="amd64"
        ;;
    i386|i686)
        ARCH_TYPE="386"
        ;;
    arm*)
        ARCH_TYPE="arm"
        ;;
    aarch64)
        ARCH_TYPE="arm64"
        ;;
    *)
        echo "Unsupported architecture: $ARCH. Please install manually."
        exit 1
        ;;
esac

case "$OS" in
    Darwin)
        OS_TYPE="darwin"
        ;;
    Linux)
        OS_TYPE="linux"
        ;;
    *)
        echo "Unsupported operating system: $OS. Please install manually."
        exit 1
        ;;
esac

# Construct the download URL based on the detected OS and architecture
DOWNLOAD_URL="$BASE_DOWNLOAD_URL-$OS_TYPE-$ARCH_TYPE"

# Determine the installation path
if [ -d "/usr/local/bin" ]; then
    INSTALL_PATH="/usr/local/bin"
elif [ -d "$HOME/.local/bin" ]; then
    INSTALL_PATH="$HOME/.local/bin"
else
    echo "Unable to find a suitable installation directory. Please install so manually."
    exit 1
fi

# Download the binary file
echo "Downloading $DOWNLOAD_URL..."
curl -sSL "$DOWNLOAD_URL" -o "so.download"

# Check if the download was successful
if [ $? -ne 0 ]; then
    echo "Download failed. Please check if the URL is correct."
    exit 1
fi

# Make the binary file executable
chmod +x "so.download"

# Move the binary file to the installation path using sudo
echo "Installing so to $INSTALL_PATH..."
sudo cp "so.download" "$INSTALL_PATH/so"

# Check if the move was successful
if [ $? -eq 0 ]; then
    echo "so installed successfully!"
else
    echo "Installation failed. Please check your permissions or install manually."
    exit 1
fi
