#!/usr/bin/env bash
XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
CONFIG="$XDG_CONFIG_HOME/huami-token.env"

_load_existing_config() {
  if [ -s "$1" ]; then
    # shellcheck disable=SC1090
    source "$1"
  fi
}

_request_credentials() {
  local -a CREDS
  # shellcheck disable=SC2046
  eval $(__credentials_dialog "$1" "$2")
  if [ ${#CREDS[@]} -eq 0 ]; then
    echo "Cancelled. $CONFIG was not changed."
    exit 0
  fi
  ZEPP_USER="${CREDS[0]//[$'\t'$'\n'$'\r']/}"
  ZEPP_PASS="${CREDS[1]//[$'\t'$'\n'$'\r']/}"
  if [ -z "$ZEPP_USER" ] || [ -z "$ZEPP_PASS" ]; then
    echo "Username or password wasn't provided. Not changing $CONFIG"
    exit 1
  fi
}

_test_credentials() {
  local auth_result
  auth_result=$(__call_huami_token "$1" "$2")

  if [ -z "$auth_result" ] || [ "$auth_result" -ne "0" ]; then
    echo Failed to login with the given user and password. Aborting.
    exit 1
  fi
}

_request_target_directory() {
  local TARGET_DIR
  if [ "$1" == "%h" ]; then
    TARGET_DIR=$HOME
  else
    TARGET_DIR=$1
  fi
  TARGET_DIR=$(__target_directory_dialog "$TARGET_DIR")
  if [ -z "$TARGET_DIR" ]; then
    echo "Cancelled. $CONFIG was not changed."
    exit 0
  fi
  TARGET_DIR=${TARGET_DIR//\\n|\\t|\\r/}
  if [ -n "$TARGET_DIR" ] && [ "$(realpath "${TARGET_DIR}")" == "$HOME" ]; then
    TARGET_DIR=%h
  else
    TARGET_DIR=$(realpath "$TARGET_DIR")
  fi
  ZEPP_AGPS_TARGET_DIR="$TARGET_DIR"
}

_save_config() {
  if [ ! -d "$XDG_CONFIG_HOME" ]; then
    mkdir "$XDG_CONFIG_HOME"
  fi
  cat <<EOF >"$CONFIG"
# Generated by configure-zepp-timer
ZEPP_USER=${ZEPP_USER@Q}
ZEPP_PASS=${ZEPP_PASS@Q}
ZEPP_AGPS_TARGET_DIR=${ZEPP_AGPS_TARGET_DIR@Q}
EOF
}

__credentials_dialog() {
  local -a CREDS
  readarray -t CREDS < <(dialog --output-fd 1 --defaultno --title "Provide Zepp login credentials" --visit-items --keep-tite --insecure --mixedform "Please enter your credentials:" 8 60 2 "Username/Email:" 1 1 "$1" 1 18 38 0 0 "Password:" 2 1 "$2" 2 18 38 0 1)
  # shellcheck disable=SC2068
  echo ${CREDS[@]@A}
}

__call_huami_token() {
  huami-token --method amazfit --email "$1" --password "$2" |& dialog --title 'Remote check' --keep-tite --programbox 'Trying to log into Zepp' 32 "$(tput cols)" 3>&1 1>&2 2>&3 3>&-
  echo "${PIPESTATUS[0]}"
}

__target_directory_dialog() {
  local RET
  RET="$(dialog --output-fd 1 --erase-on-exit --visit-items --keep-tite --clear --title "Choose a directory to put the downloaded files into" --dselect "$1/" 3 60)"
  if [ "${PIPESTATUS[0]}" -ne 0 ]; then
    RET=""
  fi
  echo "$RET"
}

main() {
  _load_existing_config "$CONFIG"
  _request_credentials "$ZEPP_USER" "$ZEPP_PASS"
  _test_credentials "$ZEPP_USER" "$ZEPP_PASS"
  _request_target_directory "$ZEPP_AGPS_TARGET_DIR"
  _save_config

  echo "The config at $CONFIG was updated"
}

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