#!/bin/bash

CLIENT_ARCHIVE_NAME="3dprinteros-client-install.zip"
INSTALL_PATH="/usr/local/3dprinteros-client"
BIN_PATH="/usr/local/bin/3dprinteros-client"
DEFAULT_BRANCH="stable3"
DEFAULT_UPDATES_SERVER="https://cli-cloud-update.3dprinteros.com"
PYTHON_VERSION=3.10

# Check if macOS Mojave or Catalina
if [[ $(sw_vers -productVersion) == 10.14* ]] || [[ $(sw_vers -productVersion) == 10.15* ]]; then
    PYTHON_VERSION=3.9
    OPENCV_VERSION="==4.5.1.48"
else
    OPENCV_VERSION=""
fi

set -e

if [ -z $1 ]; then
    BRANCH=$DEFAULT_BRANCH
else
    BRANCH=$1
    echo 3DPrinterOS Client branch: $BRANCH
fi


if [ -z $2 ]; then
    UPDATES_SERVER=$DEFAULT_UPDATES_SERVER
else
    UPDATES_SERVER=$(echo $DEFAULT_UPDATES_SERVER | sed "s/cli-cloud/$2/")
fi

if [ -d $INSTALL_PATH ] || [ -f $BIN_PATH ]; then
    echo "3DPrinterOS Client seems to be already installed."
    read -r -p " Do you wish to update/fix? [y/N] " response
        case "$response" in
            [yY][eE][sS]|[yY]) 
                ;;
            *)
                exit 0
                ;;
        esac
fi

install_brew() {

    echo "(Re)Installing 3DPrinterOS-Client..."

    if [ ! -f /usr/local/bin/brew ]; then
        echo "Installing brew..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        echo "...success"
    else
        echo "Brew is already installed. Skipping..."
    fi


    if ! command -v python$PYTHON_VERSION &> /dev/null; then
        echo "Installing Python ${PYTHON_VERSION}..."
        brew install python@$PYTHON_VERSION
        echo "...success"
    else
        echo "Python ${PYTHON_VERSION} is already installed. Skipping..."
    fi

    echo "Installing libusb..."
    brew install libusb
    echo "...success"


    echo "Installing 3DPrinterOS's python dependencies..."
    pip$PYTHON_VERSION install --upgrade --force-reinstall --prefer-binary pip aiohttp opencv-python pyusb numpy requests pyserial opencv-python$OPENCV_VERSION
    echo "...success"
}

install_client() {
    CLIENT_DOWNLOAD_URL=$(curl -sS -H "Content-Type: application/json" -d "$(printf '{\"platform\": \"mac\", \"client_version\": \"0.0.0\", \"branch\": \"%s\", \"build\": \"git\"}' $BRANCH)" $UPDATES_SERVER)
    echo Downloading from: $CLIENT_DOWNLOAD_URL

    sudo mkdir -p $INSTALL_PATH
    sudo chown -R $(whoami) $INSTALL_PATH
    curl -L $CLIENT_DOWNLOAD_URL -o $CLIENT_ARCHIVE_NAME
    unzip -o $CLIENT_ARCHIVE_NAME -d $INSTALL_PATH
    rm -f $CLIENT_ARCHIVE_NAME
    sudo sh -c "echo '#!/bin/bash\n\ncd $INSTALL_PATH\npython$PYTHON_VERSION launcher.py\n' > $BIN_PATH"
    sudo chmod +x $BIN_PATH 

    echo -e "\n\n\n\033[1m3DPrinterOS Client installation complete.\nNow you can launch it by typing: 3dprinteros-client\033[0m\n\n\n"
}

install_brew
install_client
