#!/bin/bash

source ./scripts/include/vars.sh
source ./scripts/include/sudo.sh

echo "got ROOT_DIR: $ROOT_DIR"

if [ ! -d $RELEASES_DIR ]; then
  mkdir -p $RELEASES_DIR
fi

for download_link in ${FW_VERSIONS[@]}; do
  # Get base name of the file
  tar_name=$(basename $download_link)

  # Extract tt-<version> from the tar name
  version=$(echo $tar_name | sed -n 's/.*tt\([0-9]*\).*/\1/p')

  echo $tar_name
  echo $version
  echo $platform_tar_name

  version_dir="$RELEASES_DIR/tt$version"

  echo "got version_dir: $version_dir"

  if [ ! -d $version_dir ]; then
    echo "creating dir $version_dir ..."
    mkdir $version_dir
    cd $version_dir

    echo "downloading the base tar ..."
    wget $download_link &>>/dev/null
    sudo tar -xvf $tar_name

    rm -rf $tar_name

    # Extract all .tar.gz files in their directory
    for file in $(ls | grep .tar.gz); do
      tar_dir=$(echo $file | sed -n 's/\.tar\.gz$//p')
      echo "extracting $file in $tar_dir ..."
      sudo mkdir $tar_dir
      cd $tar_dir
      sudo tar -xvf ../$file
      cd ..
    done

    sudo rm *.tar.gz
  fi

  cd $ROOT_DIR
done
