DEFAULT_UPDATES_SERVER="https://cli-cloud-update.3dprinteros.com"
DEFAULT_BRANCH=stable3
DOWNLOAD_PATH=/tmp/3dprinteros-client.zip
PYTHON=python3
PIP=pip3
DEFAULT_USER_NAME=printeros
SERVICE="3dprinteros"
SERVICE_FILENAME="$SERVICE".service

if [ -e /usr/bin/apt-get ]; then
    echo "Installing dependencies using apt-get..."
    echo "Please type sudo password"
    sudo apt-get install python3-serial python3-usb python3-opencv python3-aiohttp python3-pampy net-tools
elif [ -e /usr/bin/pacman ]; then
    echo "Installing dependencies using pacman..."
    echo "Please type sudo password"
    sudo pacman -S python-pyserial python-pyusb python-opencv python-aiohttp python-pam net-tools
    PYTHON=python
    PIP=pip
elif [ -e /usr/bin/zypper ]; then # OpenSUSE
    echo "Installing dependencies using zypper..."
    echo "Please type sudo password"
    sudo zypper in python3-pyserial python3-usb python3-opencv python3-aiohttp python3-pampy net-tools
    PYTHON=python3
    PIP=pip
elif [ -e /usr/bin/dnf ]; then # Fedora
    echo "Installing dependencies using dnf..."
    echo "Please type sudo password"
    sudo dnf install python3-pyserial python3-pyusb python3-opencv python3-aiohttp python3-pam net-tools
    PYTHON=python3
    PIP=pip
elif [ -e /usr/bin/yum ]; then # CentOS
    echo "Installing dependencies using yum..."
    echo "Please type sudo password"
    sudo yum install python3-pyserial python3-pyusb python3-opencv python3-aiohttp python3-pam net-tools
    PYTHON=python3
    PIP=pip
else
    echo "Installing python packages using pip to ~/.local folder"
    $PIP --user install requests pyserial pyusb aiohttp opencv-python numpy pam 
    if [ $? -eq 1 ]; then
        $PIP --break-system-packages install requests pyserial pyusb aiohttp opencv-python numpy pam
    fi
fi

if [ -z $1 ]; then
    BRANCH=$DEFAULT_BRANCH
else
    BRANCH=$1
    echo Installing 3DPrinterOS Client of 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

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

WD=$HOME/3dprinteros-client
mkdir -p $WD || true
echo Unpacking to: $WD
$PYTHON -m zipfile -e $DOWNLOAD_PATH $WD
rm $DOWNLOAD_PATH

echo Adding the user to groups to access printer ports and etc
sudo usermod -a -G wheel $USER
sudo usermod -a -G uucp,video $USER
sudo usermod -a -G dialout $USER || true
sudo usermod -a -G gpio $USER || true
echo 'SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", MODE="0664", GROUP="wheel"' | sudo tee /etc/udev/rules.d/99-pyusb.rules
# echo -e 'SUBSYSTEM=="meson-gpiomem", KERNEL=="gpiomem", GROUP="gpio", MODE="0660"\nSUBSYSTEM=="bcm2835-gpiomem", KERNEL=="gpiomem", GROUP="gpio", MODE="0660"\nSUBSYSTEM=="gpio*", PROGRAM="/bin/sh -c \'chown -R root:gpio /sys/class/gpio && chmod -R 660 /sys/class/gpio; chown -R root:gpio /sys/devices/virtual/gpio && chmod -R 660 /sys/devices/virtual/gpio; chown -R root:gpio /sys/devices/platform/soc/*.gpio/gpio && chmod -R 660 /sys/devices/platform/soc/*.gpio/gpio; chown -R root:gpio /sys/devices/platform/pinctrl/*.gpio/gpio && chmod -R 660 /sys/devices/platform/pinctrl/*.gpio/gpio; chown root:gpio /dev/gpiochip* && chmod 660 /dev/gpiochip*\'"\nSUBSYSTEM=="gpio", KERNEL=="gpiochip*", ACTION=="add", PROGRAM="/bin/sh -c \'chown root:gpio /sys/class/gpio/export /sys/class/gpio/unexport /dev/gpiochip* ; chmod 220 /sys/class/gpio/export /sys/class/gpio/unexport\'"\nSUBSYSTEM=="gpio", KERNEL=="gpio*", ACTION=="add", PROGRAM="/bin/sh -c \'chown root:gpio /sys%p/active_low /sys%p/direction /sys%p/edge /sys%p/value ; chmod 660 /sys%p/active_low /sys%p/direction /sys%p/edge /sys%p/value\'"' | sudo tee /etc/udev/rules.d/98-gpio.rules

if [ ! -f "${WD}"/$SERVICE_FILENAME ]; then
    curl -L https://builds.3dprinteros.com/3dprinteros.service -o $WD/3dprinteros.service
fi

echo Creating customizing and enabling service 
if [ -e /usr/local/bin/systemctl ] || [ -e /usr/bin/systemctl ]; then
    if [ "$USER" = "$DEFAULT_USER_NAME" ]; then
        SERVICE_FILE_PATH="${WD}"/$SERVICE_FILENAME
    else
        sudo mkdir -p /opt/3dprinteros || true
        SERVICE_FILE_PATH=/opt/3dprinteros/$SERVICE_FILENAME
        sudo cp "${WD}"/$SERVICE_FILENAME $SERVICE_FILE_PATH
        sudo sed -i "s/printeros/${USER}/" $SERVICE_FILE_PATH || true
        sudo sed -i "s/python/${PYTHON}/" $SERVICE_FILE_PATH || true
    fi
    sudo systemctl link $(realpath "${SERVICE_FILE_PATH}")
    sudo systemctl enable $SERVICE
    sudo systemctl start $SERVICE
    echo -e "3DPrinterOS client service is enabled - it will start automatically with your OS.\nIf you don't want this, please execute: systemctl disable $SERVICE."
elif [ -e /usr/local/bin/update-rc.d ] || [ -e /usr/bin/update-rc.d ]; then
    sudo cp $WD/3dprinteros.init.d /etc/init.d/3dprinteros
    sudo sed -i "s/home\/printeros/home\/${USER}/" /etc/init.d/3dprinteros || true
    #sudo sed -i "s/python/${PYTHON}/" /etc/init.d/3dprinteros || true
    sudo update-rc.d 3dprinteros start
    sudo update-rc.d 3dprinteros defaults
    echo -e "3DPrinterOS client service is enabled - it will start automatically with your OS.\nIf you don't want this, please execute: update-rc.d -f 3dprinteros remove. That will remove the service completely. So after this to run 3DPrinterOS Client you will have to navigate to ~/3dprinteros-client and run $PYTHON launcher.py"
fi

echo "Installation complete"
echo "Log-in with 3DPrinterOS account:"
cd $WD
$PYTHON console_login.py
if [ $? -eq 0 ]; then
    echo "Login success. 3DPrinterOS Client is ready."    
else
    echo "Login failed. You can retry with by typing: $PYTHON console_login.py"    
fi
echo "Web interface is running on ports 8008 and 8443"
