#!/usr/bin/env bash

GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

rm -rf ~/turbotabellarini
rm "$(which tabellarini)"

echo "${GREEN}Turbo tabellarini pronto alla partenza${NC}"

echo "${CYAN}Creazione cartella tabellarini${NC}"
cd
mkdir turbotabellarini
cd turbotabellarini

echo "${CYAN}Scaricamento turbo tabellarini${NC}"
WHEEL="tabellarini-0.2.5-py3-none-any.whl"
curl -LO https://ludovica.ricott.one/$WHEEL


echo "${CYAN}Turbo installazione!!${NC}"
HOMEBREW_NO_AUTO_UPDATE=true brew install pipx
HOMEBREW_NO_AUTO_UPDATE=true brew install python-tk
HOMEBREW_NO_AUTO_UPDATE=true brew install jq
pipx install --force $WHEEL
pipx ensurepath
source ~/.zprofile


echo "${CYAN}Scaricamento chromedriver${NC}"


CHROME_VERSION_FULL=$(/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version | sed 's/[^0-9]*\([0-9.]*\).*/\1/')
echo "${CYAN}Trovata versione Chrome: $CHROME_VERSION_FULL${NC}"


CHROME_MAJOR_MINOR=$(echo "$CHROME_VERSION_FULL" | cut -d. -f1,2)
JSON_URL="https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json"
JSON_DATA=$(curl -s "$JSON_URL")

MATCHED_VERSION=$(echo "$JSON_DATA" | jq -r --arg prefix "$CHROME_MAJOR_MINOR" '
  .versions[] | select(.version | startswith($prefix)) | .version' | head -n 1)

if [ -z "$MATCHED_VERSION" ]; then
  echo "${CYAN} Nessuna versione trovate per il driver${NC}"
  exit 1
fi

PLATFORM="mac-$(uname -m)"
CHROMEDRIVER_URL=https://storage.googleapis.com/chrome-for-testing-public/$MATCHED_VERSION/$PLATFORM/chromedriver-$PLATFORM.zip

FILENAME=$(basename "$CHROMEDRIVER_URL")

curl -# -O "$CHROMEDRIVER_URL"
unzip -o "$FILENAME" -d chromedriver
rm chromedriver-$PLATFORM.zip
sudo mv chromedriver/chromedriver-mac-arm64/chromedriver /usr/local/bin/chromedriver

echo "${CYAN}ChromeDriver $MATCHED_VERSION scaricato e installato.${NC}"
