#!/bin/bash

# WildlifeSystems
#
# This script is part of the WildlifeSystems project. For further information
# please refer to https://docs.wildlife.systems, or for more information on
# the project itself, please refer to https://wildlife.systems.

ws-heartbeat setup

#Setup s3cmd if .s3cfg is present
if [[ -f /boot/.s3cfg ]] || [[ -f /home/pi/.s3cfg ]]; then
  sudo apt-get install -y s3cmd
  #This is required by s3cmd but not a dependency
  sudo apt-get install -y python3-distutils
fi

#Set defaults
DEVNAME=$(pi-data hostaname)
SNDDEV="manual"
IMGDEV="manual"
PASSWD="manual"
FIREWALL="manual"

#Device serial
wsSERIAL=$(pi-data serial)

#Check if device is registered or should run as standalone
URL="https://devices.wildlife.systems/info/?id=$wsSERIAL"
response=$(curl -s -w "\n%{http_code}" $URL)
http_code=$(tail -n1 <<< "$response")  # get the last line
content=$(sed '$ d' <<< "$response")   # get all but the last line which contains the status code
if [[ $http_code == "200" ]]; then
  echo "Device found on https://devices.wildlife.systems - proceeding with automated setup"
  DEVNAME=`echo $content | jq -r '."device-name"'`
  SNDDEV=`echo $content | jq -r '."sound-device"'`
  IMGDEV=`echo $content | jq -r '."camera-type"'`
  FIREWALL=`echo $content | jq -r '."firewall"'`
else
  echo "No matching device serial number found on https://devices.wildlife.systems"
  echo "If  you want to add it before proceeding the serial number is $wsSERIAL."
fi

#Security: Default password
if [[ "$PASSWD" == "manual" ]]; then
  if [[ $(pi-data password) == "default" ]]; then
    echo "Default password (raspberry) is in use for user pi. This must be changed."
    if [[ "$1" != "unattended" ]]; then
      passwd
    fi
  fi
fi

#Security: Firewall
if [[ "$FIREWALL" == "manual" ]]; then
  echo $""
  echo "Allow SSH through the firewall? (y/n)"
  read ALLOWSSH
  if [[ "$ALLOWSSH" == "y" ]]; then
    sudo ufw allow ssh
  fi
  echo y | sudo ufw enable
else
  if [[ "$FIREWALL" == "allow-ssh-in" ]]; then
    sudo ufw allow ssh
    echo y | sudo ufw enable
  fi
fi

#Setup hostname
sudo hostnamectl set-hostname $DEVNAME

#Setup sound device
if [[ "$SNDDEV" == "manual" ]]; then
  sdc-inst list
  echo $""
  echo "Select sound device to install:"
  read SNDDEV
fi
sdc-inst $SNDDEV

#Setup imaging device
if [[ "$IMGDEV" == "manual" ]]; then
  idc-inst list
  echo $""
  echo "Select camera to install:"
  read IMGDEV
fi
idc-inst $IMGDEV

#Install ws-audio service
SERVICE_FILE="/etc/systemd/system/ws-audio.service"
if [[ ! -f "$SERVICE_FILE" ]]; then
  wget -O $SERVICE_FILE https://raw.githubusercontent.com/Wildlife-Systems/ws-node/refs/heads/master/os/all/systemd/ws-audio.service
  sudo chmod 644 $SERVICE_FILE
fi

if [[ "$1" == "unattended" ]]; then
  exit 0;
fi

#Save settings to file

#Reboot
if [[ "$1" == "unattended" ]]; then
  sudo reboot
fi
echo $""
echo "Press enter to reboot"
read REBOOT
sudo reboot
