#!/bin/bash
#
# Install and set up Oh My Zsh on Unixes, using Andrew's conventions
# and file location preferences.
#
# This covers getting the files set up locally. You'll need to do the editing
# of your ~/.zshrc yourself to get it to load up Oh My Zsh upon startup.
#
# Prerequisites:
#
#   * git (May be provided by the system, or Xcode CLT on macOS.)
#   * curl

set -o errexit
set -o nounset
set -o pipefail

MY_GITHUB_USER=apjanke

function main() {

# Install Oh My Zsh
#
# Do our own installation procedure, because their installer script breaks $PATH and may
# otherwise mess up your ~/.zshrc.

omz_repos_dir="${HOME}/local/opp/ohmyzsh"
mkdir -p "$omz_repos_dir"
if [[ ! -e "$omz_repos_dir/ohmyzsh" ]]; then
  (
    cd "$omz_repos_dir"
    echo "Cloning ohmyzsh"
    git clone https://github.com/$MY_GITHUB_USER/ohmyzsh
    cd ohmyzsh
    git remote add upstream https://github.com/ohmyzsh/ohmyzsh
    git fetch --all --tags
  )
fi
if [[ ! -e "$omz_repos_dir/ohmyzsh-custom" ]]; then
  (
    cd "$omz_repos_dir"
    # TODO: I think this will only work for public GitHub repos
    local not_found
    not_found=$(curl -s https://api.github.com/repos/$MY_GITHUB_USER/ohmyzsh-custom | grep "Not Found")
    if [[ -z "$not_found" ]]; then
      echo "Cloning ohmyzsh-custom"
      git clone https://github.com/$MY_GITHUB_USER/ohmyzsh-custom "$omz_repos_dir/ohmyzsh-custom"
    else
      echo "User $MY_GITHUB_USER has no (public) ohmyzsh-custom repo; skipping."
    fi
  )
fi
if [[ ! -e ~/.oh-my-zsh ]]; then
  echo "Linking ~/.oh-my-zsh"
  ln -s "$omz_repos_dir/ohmyzsh" ~/.oh-my-zsh
  echo "Linked ~/.oh-my-zsh. You will need to edit ~/.zshrc to source it."
else
  echo "An ~/.oh-my-zsh already exists. Not changing it."
fi
if [[ ! -e ~/.ohmyzsh-custom ]]; then
  if [[ -e "$omz_repos_dir/ohmyzsh-custom" ]]; then
    echo "Linking ~/.ohmyzsh-custom"
    ln -s "$omz_repos_dir/ohmyzsh-custom" ~/.ohmyzsh-custom
  else
    echo "No ohmyzsh-custom repo is defined under $omz_repos_dir; skipping linking"
  fi
else
  echo "An ~/.ohmyzsh-custom already exists. Not changing it."
fi

# Check that zsh is the default shell.
#
# Do not actually set it; that's too aggressive, and we can't reliably tell where
# the zsh the user would want is located.

if [[ $(uname) = Darwin ]]; then
  curr_shell=$(dscl /Search -read "/Users/$USER" UserShell | awk '{print $2}' | grep zsh 2>/dev/null)
else
  curr_shell=$(echo "$SHELL" | grep zsh 2>/dev/null)
fi
if [[ -z "$curr_shell" ]]; then
  echo "NOTE: Your current shell is not zsh. You will need to change it to zsh if you want to use oh-my-zsh."
fi

}

main
exit 0
