#!/usr/bin/env bash


## Install script for GNU/Linux & MacOS
set -e
path=/usr/local/bin

# >> Check if curl is installed or nor
if ! command -V curl > /dev/null 2>&1; then
    echo "curl not installed, please install it and try again"
    exit
fi

if ! [ -z "$1" ]; then
    path=$1
fi

echo "Download location: $path"

if [ ! -w "$path" ]; then
    SUDO="sudo"
else
    SUDO=""
fi

# Check the system architecture
case $(uname -m) in
    x86_64) ARCH="amd64"   ;;
    i386 | i686) ARCH="i386"   ;;
    arm64 | aarch64) ARCH="arm64"   ;;
    arm | armv7l) ARCH="armv7l" ;;
    *) echo "Unsupported architecture: $(uname -m)"; exit 1   ;;
esac

# Check if the system is macOS
if [[ $(uname -s) == "Darwin" ]]; then
    OS="mac"
else
    OS="linux"
fi

[ -e /tmp/tgpt ] && rm /tmp/tgpt

echo "Operating System: ${OS}"
echo -e "Processor Architecture: ${ARCH}\n"
# Set the URL of the executable based on the architecture and OS
URL="https://github.com/aandrew-me/tgpt/releases/latest/download/tgpt-${OS}-${ARCH}"
# Download the executable
echo -e "Downloading...\n"
curl -SL --progress-bar "$URL" -o /tmp/tgpt

# Move the executable to a directory in PATH (e.g. /usr/local/bin/ on Linux, /usr/local/bin/ or /usr/local/opt/ on macOS)
$SUDO mv /tmp/tgpt $path

if [ -d "$path" ]; then
    $SUDO chmod +x $path/tgpt
    elif [ -f "$path" ]; then
    $SUDO chmod +x $path
fi

echo -e "Installed Successfully \n"

if [[ $path != "/usr/local/bin" ]]; then
    echo "Make sure your file is in PATH"
    echo "Run tgpt -h for help"
else
    echo -e "Run tgpt -h for help"
fi
