#!/bin/bash

#Prototype          10.2.3.115         Prototype
#Salimax0001        10.2.3.104         Marti Technik (Bern)
#Salimax0002        10.2.4.29          Weidmann d (ZG)
#Salimax0003        10.2.4.33          Elektrotechnik Stefan GmbH
#Salimax0004        10.2.4.32          Biohof Gubelmann (Walde)
#Salimax0005        10.2.4.36          Schreinerei Schönthal (Thun)
#Salimax0006        10.2.4.35          Steakhouse Mettmenstetten
#Salimax0007        10.2.4.154         LerchenhofHerr Twannberg 
#Salimax0008        10.2.4.113         Wittmann Kottingbrunn

dotnet_version='net6.0'
ip_address="$1"
battery_ids="$2"
username='ie-entwicklung'
root_password='Salimax4x25'

if [ "$#" -lt 2 ]; then
  echo "Error: Insufficient arguments. Usage: $0 <ip_address> <battery_ids>"
  exit 1
fi

# Function to expand battery ids from a range
expand_battery_ids() {
  local range="$1"
  local expanded_ids=()

  IFS='-' read -r start end <<< "$range"
  for ((i = start; i <= end; i++)); do
    expanded_ids+=("$i")
  done

  echo "${expanded_ids[@]}"
}

# Check if battery_ids_arg contains a hyphen indicating a range
if [[ "$battery_ids" == *-* ]]; then
  # Expand battery ids from the range
  battery_ids=$(expand_battery_ids "$battery_ids")
else
  # Use the provided battery ids
  battery_ids=("$battery_ids")
fi

echo "ip_address: $ip_address"
echo "Battery_ids: ${battery_ids[@]}"

#ip_addresses=("10.2.3.115" "10.2.3.104" "10.2.4.33" "10.2.4.32" "10.2.4.36" "10.2.4.35" "10.2.4.154" "10.2.4.113" "10.2.4.29")
#battery_ids=("2" "3" "4" "5" "6" "7" "8" "9" "10" "11")

set -e

scp download-bms-log "$username"@"$ip_address":/home/"$username"
ssh "$username"@"$ip_address" "echo '$root_password' | sudo -S systemctl stop battery.service"
ssh "$username"@"$ip_address" "echo '$root_password' | sudo -S apt install python3-pip -y"
ssh "$username"@"$ip_address" "echo '$root_password' | sudo -S pip3 install pymodbus"

for battery in "${battery_ids[@]}"; do
    ssh "$username"@"$ip_address" "echo '$root_password' | sudo -S python3 download-bms-log " "$battery" " ttyUSB0" 
done
ssh "$username"@"$ip_address" "echo '$root_password' | sudo -S systemctl start battery.service"
ssh "$username"@"$ip_address" "echo '$root_password' | sudo -S rm download-bms-log"
scp "$username"@"$ip_address":/home/"$username/*.bin" .
ssh "$username"@"$ip_address" "echo '$root_password' | sudo -S rm *.bin"

echo "Deployed and ran commands on $ip_address"
done