#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# Update and install necessary packages
echo "Updating package list and installing necessary packages..."
sudo apt update
sudo apt install -y git gh apache2 php python3 python3-pip jq autossh i2c-tools python3-smbus

# Install Python libraries
echo "Installing Python libraries..."
sudo pip3 install pyserial requests RPi.GPIO adafruit-circuitpython-bme280 --break-system-packages

# Set up SSH for /var/www
echo "Setting up SSH keys..."
sudo mkdir -p /var/www/.ssh
sudo ssh-keygen -t rsa -b 4096 -f /var/www/.ssh/id_rsa -N ""
sudo ssh-copy-id -i /var/www/.ssh/id_rsa.pub -p 50221 airlab_server1@aircarto.fr


# Clone the repository
echo "Cloning the NebuleAir Pro 4G repository..."
sudo git clone http://gitea.aircarto.fr/PaulVua/nebuleair_pro_4g.git /var/www/nebuleair_pro_4g

# Set up repository files and permissions
echo "Setting up repository files and permissions..."
sudo mkdir -p /var/www/nebuleair_pro_4g/logs
sudo touch /var/www/nebuleair_pro_4g/logs/app.log /var/www/nebuleair_pro_4g/logs/loop.log
sudo cp /var/www/nebuleair_pro_4g/config.json.dist /var/www/nebuleair_pro_4g/config.json
sudo chmod -R 777 /var/www/nebuleair_pro_4g/
git config core.fileMode false

# Set up cron jobs
echo "Setting up cron jobs..."
sudo crontab /var/www/nebuleair_pro_4g/cron_jobs

echo "Setup completed successfully!"
