#!/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"

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 [ brew list python@3 &>/dev/null ]; then
        echo "Installing Python..."
        brew install python@3
        echo "...success"
    else
        echo "Reinstalling Python..."
        brew reinstall python@3
        echo "...success"
    fi

    if [ brew list lisbusb@3 &>/dev/null ]; then
        echo "Installing libusb..."
        brew install libusb@3
        echo "...success"
    else
        echo "Reinstalling lisusb..."
        brew reinstall libusb@3
        echo "...success"
    fi

    echo "Installing 3DPrinterOS's python dependencies..."
    pip3 install --upgrade --force-reinstall aiohttp opencv-python pyusb numpy requests pyserial pillow
    echo "...success"
}

install_client() {
    CLIENT_DOWNLOAD_URL=$(curl -sS -H "Content-Type: application/json" -d "$(printf '{\"platform\": \"rpi\", \"client_version\": \"0.0.0\", \"branch\": \"%s\", \"build\": \"git\"}' $BRANCH)" https://acorn-update.3dprinteros.com)
    echo Downloading from: $CLIENT_DOWNLOAD_URL

    mkdir -p $INSTALL_PATH
    curl -L $CLIENT_DOWNLOAD_URL -o $CLIENT_ARCHIVE_NAME
    unzip -o $CLIENT_ARCHIVE_NAME -d $INSTALL_PATH

    rm -f $CLIENT_ARCHIVE_NAME
    echo -e "#!/bin/bash\n\ncd $INSTALL_PATH\npython3 launcher.py\n" > $BIN_PATH
    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
