#!/bin/bash

# This script is generated by Terminalwire. You
# can run it from your console:
#
#   $ curl -sSL https://tinyzap.terminalwire.sh/ | bash
#
# It will:
#
#   1. Detect the operating system and architecture
#      of your system.
#   2. Download the Terminalwire CLI for those specs.
#   3. Install it on your system at ~/.terminalwire
#      (or $TERMINALWIRE_PATH).
#   4. Modify your shell initialization files to
#      include Terminalwire in your $PATH.
#   5. Verify the installation.
#   6. Install the tinyzap application.
#
#  Read the code below if you want to know exactly
#  what it will do. If you're not sure, don't run it.
#
#  For more information go to https://terminalwire.com.
#
#  And now ladies and gentlemen, the script:

set -euo pipefail

ARCH=$(uname -m)
OS=$(uname -s)
URL="https://tinyzap.terminalwire.sh/bash/builds/2"
TERMINALWIRE_PATH="${TERMINALWIRE_PATH:-$HOME/.terminalwire}"
TERMINALWIRE_HOME="$HOME/.terminalwire"
# Export variables so `terminalwire` commands can use them.
PATH="$TERMINALWIRE_PATH/bin:$PATH"

# Function to download using curl or wget
get(){
  # Detect curl on system.
  if command -v curl >/dev/null 2>&1; then
    curl  --progress-bar \
          --fail-with-body \
          -L \
          -H "X-Arch: $ARCH" \
          -H "X-OS: $OS" \
          "$1"
  # Detect wget on system.
  elif command -v wget >/dev/null 2>&1; then
    wget  --quiet \
          --show-progress \
          --header="X-Arch: $ARCH" \
          --header="X-OS: $OS" \
          -O - "$1" || exit 1 # Exit on error
  # Show an error and exit if none are available.
  else
    echo "Error: Neither curl nor wget is available on this system." >&2
    exit 1
  fi
}


# Show the detected operating system and architecture.
echo "Detected Operating System: $OS"
echo "Detected Architecture: $ARCH"
echo

# Create terminalwire directory if it doesn't exist.
mkdir -p "$TERMINALWIRE_PATH"

echo "Downloading $URL and extracting to $TERMINALWIRE_PATH."

# Download and extract the Terminalwire CLI package to the terminalwire directory.
get "$URL" | tar -xz -C "$TERMINALWIRE_PATH"
echo

# Configures shell initialization files to include Terminalwire in the PATH
# and creates folders for Terminalwire binary stubs.
terminalwire setup terminal \
  --path "$TERMINALWIRE_PATH" \
  --shell "$SHELL"

# Install the tinyzap application.
terminalwire install tinyzap

# That's it! Enjoy using Terminalwire.
#
# ❤️
