#!/bin/bash

echo "🪄✨ Welcome to the Twilio CLI Magic Installer! Sit back, relax, and let the magic happen... ✨🪄"

# Define variables
TWILIO_CLI_URL="https://github.com/twilio/twilio-cli/releases/latest/download/twilio-cli-linux-x64.tar.gz"
DOWNLOAD_DIR="/tmp"
BINARY_NAME="twilio"
TARGET_DIR="/usr/local/bin"
ARCHIVE_NAME="twilio-cli-linux-x64.tar.gz"

# Step 1: Download the Twilio CLI tarball
echo "📥 Downloading Twilio CLI from the mystical GitHub realms..."
curl -L $TWILIO_CLI_URL -o $DOWNLOAD_DIR/$ARCHIVE_NAME || { echo "❌ Download failed. Please check your internet spellbook."; exit 1; }

# Step 2: Verify the downloaded file
echo "🔍 Inspecting the artifact for magical properties..."
FILE_TYPE=$(file $DOWNLOAD_DIR/$ARCHIVE_NAME)
if [[ ! $FILE_TYPE == *"gzip compressed data"* ]]; then
  echo "❌ Uh-oh! The artifact is cursed (or just not a valid .tar.gz file). Exiting now to avoid any hexes."
  exit 1
fi

# Step 3: Extract the archive
echo "🛠️ Extracting the Twilio CLI treasure chest..."
tar -xvzf $DOWNLOAD_DIR/$ARCHIVE_NAME -C $DOWNLOAD_DIR || { echo "❌ Extraction spell failed."; exit 1; }

# Step 4: Move the binary to the target directory
echo "🚚 Moving the Twilio CLI to its throne at $TARGET_DIR..."
sudo mv $DOWNLOAD_DIR/$BINARY_NAME $TARGET_DIR || { echo "❌ Couldn't move the CLI to its castle."; exit 1; }

# Step 5: Verify installation
echo "✅ Checking if the Twilio CLI is ready for action..."
if command -v $BINARY_NAME &> /dev/null; then
  echo "🎉 Success! Twilio CLI is alive and well! Here's its version:"
  $BINARY_NAME --version
else
  echo "❌ Twilio CLI seems to have ghosted us. Try again?"
  exit 1
fi

# Step 6: Cleanup
echo "🧹 Tidying up leftover bits and bobs..."
rm -f $DOWNLOAD_DIR/$ARCHIVE_NAME
echo "✨ All clean. Your Twilio CLI is ready to dazzle!"

echo "🎩 Ta-da! You've installed Twilio CLI with flair. Now go make some magic calls! 📞✨"

