#!/bin/bash
# exit on errors
set -e
# Check that we are root
if [[ ! $(whoami) == 'root' ]]; then
  echo 'This is intended to be ran as root'
  exit 1
fi

# Check if the truetool repo already exists
if [[ -d $HOME/truetool ]]; then
  cd "$HOME/truetool" || exit
  git log -n1|cat
else
  cd "$HOME" || exit
  git clone https://github.com/truecharts/truetool.git
fi

# Check if $HOME/bin exists, or make it
if [[ ! -d $HOME/bin ]]; then
  mkdir -p "$HOME/bin"
fi

# Check if the truetool wrapper exists, or make it
if [[ ! -x "$HOME/bin/truetool" ]]; then
  install -m555 -v "$HOME/truetool/bin/truetool" "$HOME/bin/"
fi

# these vars are used by the following functions
LINE_TO_ADD=''
TARGET_FILE_FOR_ADD="$HOME/.profile"

check_if_line_exists()
{
  if [[ "$VERBOSITY" -gt '7' ]]; then
    echo "Checking for '$LINE_TO_ADD'  in $TARGET_FILE_FOR_ADD"
  fi
  grep -qsFx "$LINE_TO_ADD" "$TARGET_FILE_FOR_ADD"
}

add_line_to()
{
  if [[ "$VERBOSITY" -gt '5' ]]; then
    echo "Adding '$LINE_TO_ADD'  to $TARGET_FILE_FOR_ADD"
  fi
  TARGET_FILE=$TARGET_FILE_FOR_ADD
    [ -w "$TARGET_FILE" ] || TARGET_FILE=$TARGET_FILE_FOR_ADD
    printf "%s\n" "$LINE_TO_ADD" >> "$TARGET_FILE"
}

dotfiles_install () {
  # Adjusting dotfiles by adding $HOME/bin to our path
  touch "$HOME/.zshrc"
  touch "$HOME/.bashrc"
  LINE_TO_ADD="$(printf "export PATH=\"%s:\$PATH\"" '/root/bin')"
  TARGET_FILE_FOR_ADD="$HOME/.bashrc"
  check_if_line_exists || add_line_to
  TARGET_FILE_FOR_ADD="$HOME/.zshrc"
  check_if_line_exists || add_line_to
}

dotfiles_install