#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# ──────────────────────────────────────────────────────────────────────────────
# $source: cappysan-dotfile-scripts$
# ──────────────────────────────────────────────────────────────────────────────
#
# Set DEBUG=1 to not clear the screen when script stops
#
set -u -o pipefail
export PS4=""

# HOME must be set
if builtin test -z "${HOME:-}"; then
  echo 'error: HOME is not set. Set it and export it, and run script again' >&2
  echo '       eg: export HOME=/home/jdoe' >&2
  exit 1
fi

# Set PATH to system's absolute default
export OLDPATH="${PATH}"
export PATH=$(env -i dash -c 'echo ${PATH}')

# Change directory to HOME
cd ${HOME}

export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"

# Verify that we have write access to environment
mkdir -p  ${XDG_CONFIG_HOME}/environment.d/
chmod 700 ${XDG_CONFIG_HOME}

# Require dialog first
if ! type -pP dialog >/dev/null; then
  echo 'error: apt package "dialog" must be installed' >&2
  echo '       eg: "sudo apt-get install -y --no-install-recommends dialog"' >&2
  exit 1
fi
if ! type -pP pipx >/dev/null; then
  echo 'error: apt package "pipx" must be installed' >&2
  echo '       eg: "sudo apt-get install -y --no-install-recommends pipx"' >&2
  exit 1
fi
if ! type -pP vcsh >/dev/null; then
  echo 'error: apt package "vcsh" must be installed' >&2
  echo '       eg: "sudo apt-get install -y --no-install-recommends vcsh"' >&2
  exit 1
fi

# We need to find where we are installed, to be able to source ourselves
# Returns ~/.local/pipx or ~/.local/share/pipx
export as_root=$(pipx list | head -1 | cut -d' ' -f4)
version=$(cat "${as_root}/cappysan-dotfile-scripts/pyvenv.cfg" | grep ^version | cut -d= -f2 | xargs | cut -d. -f1,2)
if test "x$version" = "x"; then
  echo "error: failed to get python version" >&2
fi

as_root="${as_root}/cappysan-dotfile-scripts"
as_root="${as_root}/lib/python${version}/site-packages/dotfiles/share"
if test ! -d "${as_root}"; then
  echo 'error: root "share" folder not found' >&2
  exit 1
fi

# Dialog's will use a temp file for output
as_output=$(mktemp)
if test "${DEBUG:-}" == ""; then
  trap "rm -f \"${as_output}\"; dialog --clear" 0 1 2 3 15
fi

source ${as_root}/functions.sh

_as_eval_dirs ${as_root}/setup.d
_as_cleanup
