#!/usr/bin/env bash

apply_dotfile() {
  directory_to_stow="${1}"
  stow --adopt -S -t "${HOME}" "${directory_to_stow}"
}

revert_dotfile() {
  directory_to_stow="${1}"
  stow -D -t "${HOME}" "${directory_to_stow}"
}

# Adopt will change the files in stow to match existing files.
# We don't want this, we just want to handle existing files gracefully.
# We simply adopt all the files and then at the end restore our git repo to undo changes
restore_from_adoption() {
  git restore .
}

mode_command=${1:-apply}
if [ "${mode_command}" != "apply" ] && [ "${mode_command}" != "revert" ]; then
  echo "$0: mode command ("'${1}'") must be apply or revert" 1>&2
  exit 1
fi

operation() {
  ${mode_command}_dotfile ${1}
}

# Create .local/bin to prevent tree folding
mkdir -p ~/.local/bin

operation bash
operation sh
operation readline
operation screen

operation git
operation xdg

operation vim

operation ruby
operation python

# Only if inside a coder instance
if [ -n "${CODER}" ]; then
  operation gnupg
fi

# Check that SSH version is above 9.2 (where EnableEscapeCommandline was added) before conditionally adding
# a config file. This is then included in the main config
SSH_VERSION=$(ssh -V 2>&1 | cut -d',' -f 1 | cut -d '_' -f 2)
if [[ "${SSH_VERSION}" =~ ^9\.[1-9]{0,1}[2-9].*$ ]]; then
cat <<CONFIG > ssh/.ssh/extra.conf
EnableEscapeCommandline yes
CONFIG
fi
operation ssh

restore_from_adoption
