#!/usr/bin/env bash

# Experimental App Studio setup script.

# Invoke with curl https://raw.githubusercontent.com/mar-hol/dotfiles/main/appstudiosetup | bash
# when in the terminal of a new App Studio dev space.

set -o errexit

# Script-global vars
declare dotfiles="$HOME/.dotfiles"
declare backupdir="$HOME/.appstudiosetup.backups"
declare execdir="$HOME/bin"
declare jqrelease="jq-1.6"
# TODO declare gorelease, osplatform

#
# Make backup of a file (not even sure if backups are really neccessary,
# as this is for a freshly minted dev space.
# Note path chars (/) are turned into dashes.
backup() {
  if [[ -e "$HOME/$1" ]]; then
    local file
    file="$(echo "$1" | tr '\/' '-')"
    cp "$HOME/$1" "$backupdir/$file"
  fi
}

# Bring in and set up dotfiles
setup_dotfiles() {
  rm -rf "$dotfiles"
  git clone https://github.com/qmacro/dotfiles.git "$dotfiles"
  ln -s -f "$dotfiles/bashrc" "$HOME/.bashrc"
}

setup_dirs() {
  [[ -d "$backupdir" ]] || mkdir "$backupdir"
  [[ -d "$execdir" ]] || mkdir "$execdir"
}

# Configure dev space as I like it
modify_theia_settings() {
  cp "$dotfiles/.theia/settings.json" "$HOME/.theia/settings.json"
}

# Install common utilities
# ------------------------

install_utils() {
  # jq - for JSON parsing and manipulation
  local target="$execdir/jq"
  curl -L "https://github.com/stedolan/jq/releases/download/${jqrelease}/jq-linux64" > "$target" && chmod +x "$target"

  # jwt - for decoding JSON Web Tokens (OAuth access tokens)
  npm install --global jwt-cli

  # Bash git prompt - to show git repository status on the command line prompt
  git clone https://github.com/magicmonty/bash-git-prompt.git ~/.bash-git-prompt --depth=1
  
  # Install https://github.com/danielgtaylor/restish/releases/tag/v0.4.4
  # todo download the needed zip-archive, unpack and install in /home/bin or something like this

  # Install latest version of GO
  # https://golang.org/dl/go1.15.4.linux-amd64.tar.gz
  # https://golang.org/doc/install ->  tar -C /usr/local -xzf go1.15.4.linux-amd64.tar.gz
  #local traget_go="$execdir/go"
  #curl -L https://golang.org/dl/${gorelease}.${osplatform}.tar.gz > "$target/${gorelease}.${osplatform}.tar.gz" | tar -C "$target" -xzf go1.15.4.linux-amd64.tar.gz
  #curl -L https://golang.org/dl/go1.15.4.linux-amd64.tar.gz > $HOME/bin/go2/go1.15.4.linux-amd64.tar.gz  | tar -C /home/user/bin/go2 -xzf go1.15.4.linux-amd64.tar.gzs
  # cealn up => remove archive file
}

main() {

  setup_dirs

  backup ".bashrc"
  backup ".theia/settings.json"

  setup_dotfiles

  modify_theia_settings

  install_utils

}

main "$@"