#!/bin/bash

# This scripts serves the function of installing the Picockpit-Client.
# Depending on whether it is downloaded from the frontend inside your own account or from picockpit.com/setup.sh it will either ask you for an API key or run automatically.

readonly OTK="$$$OTK$$$"
readonly PI_NAME="$$$PINAME$$$"

# Adding our key to your keyring.
curl -L http://repository.picockpit.com/picockpit.public.key | sudo gpg --dearmour | sudo tee /usr/share/keyrings/picockpit.gpg 2>&1 > /dev/null

os_release=$(lsb_release -cs)

case $os_release in
   "buster") repo='deb [arch=arm64,armhf signed-by=/usr/share/keyrings/picockpit.gpg] http://repository.picockpit.com/debian/ buster main';;
   "bullseye") repo='deb [arch=arm64,armhf signed-by=/usr/share/keyrings/picockpit.gpg] http://repository.picockpit.com/debian/ bullseye main';;
   "bookworm") repo='deb [arch=arm64,armhf signed-by=/usr/share/keyrings/picockpit.gpg] http://repository.picockpit.com/debian/ bookworm main';;
   *) echo 'There is a problem with reading the installed version via lsb_release. This installation script is intended for Raspberry Pi OS based either on Buster, Bullseye or Bookworm. We recommend using Bookworm.';;
esac

# Since we are currently only using one repository, we just overwrite the current source (if it exists) and add the new one.
echo "$repo" | sudo tee /etc/apt/sources.list.d/picockpit.list 2>&1 > /dev/null

# After making sure the repository exists we simply update and install with apt-get.
sudo apt-get update 2>&1 > /dev/null
echo "Installing Picockpit-Client from our Repo. This step might take a minute."
sudo apt-get install picockpit-client 2>&1 > /dev/null



if dpkg -l "picockpit-client"; then
  echo "picockpit-client was installed succesfully."
else
  echo "Something during the installation went wrong. Please reach out to us at support@picockpit.com if you suspect an issue on our side!"
  exit 1
fi

# As a last step we call the connect function of the picockpit-client.
if [ ${#OTK} == 41 ]; then
	sudo picockpit-client connect-otk --otk "$OTK" --name "$PI_NAME"
else
	echo "At this stage in the installation we ask you for an API-Key. If you aren't sure where to find it please look at https://picockpit.com/raspberry-pi/installation-of-picockpit/"
	sudo picockpit-client connect
fi

sudo systemctl enable picockpit-client.service
sudo systemctl restart picockpit-client.service

# copyright 2023

# IN NO EVENT WILL pi3g e.K. BE LIABLE FOR ANY INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES,
# INCLUDING WITHOUT LIMITATION DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER INTANGIBLE LOSSES,
# ARISING UNDER OR RELATING TO THIS AGREEMENT OR FROM THE USE OF, OR INABILITY TO USE, THE SERVICE.

# When in doubt do not use this software and service.
