#!/bin/bash

# Script to set up the App after rebooting

# Exit on error, unset variable usage, and error in a pipeline
set -euo pipefail

# Define color variables
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No color

# Function to print messages in color
info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# Check for root privileges
if [[ "$EUID" -ne 0 ]]; then
    error "This script must be run as root. Use 'sudo ./installation.sh'"
fi
REPO_DIR="/var/www/nebuleair_pro_4g"
#set up the RTC
info "Set up the RTC"
/usr/bin/python3 /var/www/nebuleair_pro_4g/RTC/set_with_NTP.py

#Wake up SARA
info "Wake Up SARA"
pinctrl set 16 op
pinctrl set 16 dh

info "Waiting for SARA to wake up..."
for i in {1..8}; do
  echo -ne "  $i/8 seconds\r"
  sleep 1
done
echo -e "\n"

#Check SARA connection (ATI)
info "Check SARA connection (ATI)"
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara.py ttyAMA2 ATI 2 || warning "SARA not detected (ATI). Continuing..."

sleep 1

#set up SARA R4 APN
#info "Set up Monogoto APN"
#/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara_setAPN.py ttyAMA2 data.mono 2

#activate blue network led on the SARA R4
info "Activate blue LED"
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara.py ttyAMA2 AT+UGPIOC=16,2 2 || warning "SARA LED activation failed. Continuing..."

sleep 1

#get SIM card CCID
info "Get SIM card CCID"
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara.py ttyAMA2 AT+CCID? 2 || warning "SARA CCID read failed. Continuing..."

sleep 1

#get SIM card IMSI
info "Get SIM card IMSI"
imsi_output=$(/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara.py ttyAMA2 AT+CIMI 2 2>&1) || warning "SARA IMSI read failed. Continuing..."
echo "$imsi_output"
# Extract IMSI (15-digit numeric string)
imsi_number=$(echo "$imsi_output" | grep -oP '^\d{15}$' || echo "N/A")

#Connect to network
#info "Connect SARA R4 to network"
#python3 /var/www/nebuleair_pro_4g/SARA/sara_connectNetwork.py ttyAMA2 20810 60

# Set up all systemd services (SARA, NPM, BME280, RTC save_to_db, etc.)
# Single source of truth: services/setup_services.sh
info "Setting up systemd services..."

if [[ -f "$REPO_DIR/services/setup_services.sh" ]]; then
    sudo chmod +x "$REPO_DIR/services/setup_services.sh"
    sudo "$REPO_DIR/services/setup_services.sh" || warning "Failed to set up systemd services"
    success "Systemd services set up successfully."
else
    warning "Systemd services setup script not found."
fi

# Display device information
echo ""
echo "=========================================="
echo -e "${GREEN}    Installation Complete!${NC}"
echo "=========================================="

# Get Raspberry Pi serial number (last 8 characters)
serial_number=$(cat /proc/cpuinfo | grep Serial | awk '{print substr($3, length($3) - 7)}' | tr '[:lower:]' '[:upper:]')
echo -e "${BLUE}Device ID (Serial):${NC} $serial_number"

# Display IMSI
echo -e "${BLUE}IMSI:${NC}               ${imsi_number:-N/A}"

# Get IP address and make it a clickable link
ip_wlan0=$(ip -4 addr show wlan0 2>/dev/null | grep -oP '(?<=inet\s)\d+(\.\d+){3}' || echo "Not connected")

if [[ "$ip_wlan0" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    admin_url="http://${ip_wlan0}/html/admin.html"
    echo -e "${BLUE}IP Address (wlan0):${NC} ${admin_url}"
else
    echo -e "${BLUE}IP Address (wlan0):${NC} $ip_wlan0"
fi

echo "=========================================="
