#!/bin/bash

VERSION="$1"
BINARY="$2"
OS="$3"
ARCH="$4"

BASE_URL=https://fermah-releases.s3.us-east-2.amazonaws.com

URL_RELEASE=$BASE_URL/$VERSION/$BINARY-$OS-$ARCH.tar.gz

HOME_DIR=~/.fermah

BINARY_FOLDER=bin

BINARY_DIR="$HOME_DIR/$BINARY_FOLDER"

TEMP_DIR=$(mktemp -d)
TEMP_FILE=release.tar.gz

magenta() {
  echo -e "\033[35m"
}

green() {
  echo -e "\033[32m"
}

reset() {
  echo -e "\033[0m"
}

magenta

echo "Downloading fermah-$BINARY release from $URL_RELEASE"

green

if ! wget -q --show-progress -O "$TEMP_DIR/$TEMP_FILE" "$URL_RELEASE"; then
  echo "Release not found for version, binary, os and arch combination"
  reset
  exit 1;
fi

magenta

echo "Unzipping.."
tar xzvf "$TEMP_DIR/$TEMP_FILE" -C "$TEMP_DIR"

mkdir -p $BINARY_DIR

echo "Installing fermah-$BINARY to $BINARY_DIR"
cp "$TEMP_DIR/$BINARY" "$BINARY_DIR/fermah-$BINARY-$VERSION"

echo "Linking fermah-$BINARY to downloaded version at $BINARY_DIR/fermah-$BINARY-$VERSION"
ln -sf $BINARY_DIR/fermah-"$BINARY"-"$VERSION" $BINARY_DIR/fermah-"$BINARY"

echo "Copying configuration files to $HOME_DIR"
cp -r "$TEMP_DIR/config" "$HOME_DIR"

rm -rf "$TEMP_DIR"

green

echo -e "\xE2\x9C\x94 Done!"

echo ""
echo "---------------------------------------------------------------"
echo "You may add the binary to your PATH with the following command:"
echo ""

USER_DIR=$(eval echo ~"$USER")/.fermah/$BINARY_FOLDER

if [[ $SHELL == *"bash"* ]]; then
    echo "  echo 'export PATH=\"\$PATH:$USER_DIR\"' >> ~/.bashrc"
    echo "  source ~/.bashrc"
elif [[ $SHELL == *"zsh"* ]]; then
    echo "  echo 'export PATH=\"\$PATH:$USER_DIR\"' >> ~/.zshrc"
    echo "  source ~/.zshrc"
else
    echo "  echo 'export PATH=\"\$PATH:$USER_DIR\"' >> ~/.profile"
    echo "  source ~/.profile"
fi

reset
