#!/usr/bin/env bash

set -eu

main(){
  if [ "$(uname)" == "Darwin" ]; then
    mac_install
    touch ~/.zshrc
  elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
    linux_install
  fi
  install_nvm
}

mac_install(){
    # Install Brew
  if ! hash brew > /dev/null 2>&1; then
    echo "Brew not installed! Installing..."
    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  fi

  # Install Yarn
  if ! brew ls --versions yarn > /dev/null 2>&1; then
    brew install yarn
  fi
  if ! brew ls --versions coreutils > /dev/null; then
    brew install coreutils
  fi
  if ! brew ls --versions libtool > /dev/null 2>&1; then
    brew install libtool
  fi
  if ! brew ls --versions automake > /dev/null 2>&1; then
    brew install automake
  fi
  if ! brew ls --versions autoconf > /dev/null 2>&1; then
    brew install autoconf
  fi
  if ! hash x265 > /dev/null 2>&1; then
    brew install x265
  fi
  sudo () {
    [[ $EUID = 0 ]] || set -- command sudo "$@"
    "$@"
  }
  if ! hash pip3 > /dev/null 2>&1; then
    sudo easy_install pip
  fi
  python3 -m pip install --user pyyaml
}

linux_install(){
  # Run with sudo if not root
  sudo () {
    [[ $EUID = 0 ]] || set -- command sudo "$@"
    "$@"
  }
  sudo apt update
  sudo apt install --assume-yes build-essential autoconf automake libtool
  sudo pip install pyyaml
}

install_nvm(){
  echo "Installing nvm..."

  curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash

  export NVM_DIR="$HOME/.nvm"
  [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" --no-use
}

main
