#!/usr/bin/env bash
DROPIN_FILE="$1/huami-token.service.d/01-set-working-directory.conf"

function disable_unit_and_exit() {
  local TIMER_LINK="$XDG_CONFIG_HOME/systemd/user/timers.target.wants/huami-token.timer"
  if [ -h "$TIMER_LINK" ]; then
    rm -f "$TIMER_LINK"
  fi
  if [ -f "$DROPIN_FILE" ]; then
    rm -f "$DROPIN_FILE"
  fi
  exit 0
}

main() {
  local XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
  local CONFIG="$XDG_CONFIG_HOME/huami-token.env"
  # Generate the WorkingDir value for the huami-token user service unit
  if [ ! -s "$CONFIG" ]; then
    disable_unit_and_exit
  fi

  # shellcheck disable=SC1090
  source "$CONFIG"
  if [ -z "${ZEPP_AGPS_TARGET_DIR//[$'\t'$'\n'$'\r']/}" ]; then
    disable_unit_and_exit
  fi

  mkdir -p "$(dirname "$DROPIN_FILE")"
  cat <<EOF >"$DROPIN_FILE"
# Generated by huami-token-generator
[Service]
WorkingDirectory=${ZEPP_AGPS_TARGET_DIR}
EOF
}

# Check if the script is being run directly, not sourced
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  main "$@"
fi
