#!/bin/sh
set -eu

VERSION="0.0.46"
ZIP_NAME="FailureNTS_V0.0.46_public.zip"
BASE_URL="${FAILURENTS_BASE_URL:-http://failurenetworks.net/failurents}"
ZIP_URL="$BASE_URL/downloads/$ZIP_NAME"

say() { printf '%s\n' "$*"; }
fail() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }

CONFIG_DIR="${1:-${HA_CONFIG_DIR:-}}"

if [ -z "$CONFIG_DIR" ]; then
  if [ -f ./configuration.yaml ]; then
    CONFIG_DIR="$(pwd)"
  elif [ -f /config/configuration.yaml ] || [ -d /config/custom_components ] || [ -d /config/www ]; then
    CONFIG_DIR="/config"
  else
    fail "Could not find Home Assistant config directory. Run from /config or pass path: sh install.sh /config"
  fi
fi

[ -d "$CONFIG_DIR" ] || fail "Config directory does not exist: $CONFIG_DIR"

TMP_DIR="$(mktemp -d)"
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT INT TERM

say "FailureNTS™ installer v$VERSION"
say "Config dir: $CONFIG_DIR"
say "Download: $ZIP_URL"

if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$ZIP_URL" -o "$TMP_DIR/$ZIP_NAME"
elif command -v wget >/dev/null 2>&1; then
  wget -q -O "$TMP_DIR/$ZIP_NAME" "$ZIP_URL"
else
  fail "Need curl or wget to download $ZIP_URL"
fi

if command -v unzip >/dev/null 2>&1; then
  unzip -q "$TMP_DIR/$ZIP_NAME" -d "$TMP_DIR/pkg"
else
  fail "Need unzip. Install unzip or extract the package manually."
fi

SRC="$TMP_DIR/pkg"
# Support both direct-root zips and zips that contain one top folder.
if [ ! -d "$SRC/custom_components/note_to_self" ]; then
  ONE_DIR="$(find "$SRC" -mindepth 1 -maxdepth 1 -type d | head -n 1 || true)"
  if [ -n "$ONE_DIR" ] && [ -d "$ONE_DIR/custom_components/note_to_self" ]; then
    SRC="$ONE_DIR"
  fi
fi

[ -d "$SRC/custom_components/note_to_self" ] || fail "Package is missing custom_components/note_to_self"
[ -d "$SRC/www/note-to-self" ] || fail "Package is missing www/note-to-self"

mkdir -p "$CONFIG_DIR/custom_components" "$CONFIG_DIR/www"
STAMP="$(date +%Y%m%d-%H%M%S)"

if [ -d "$CONFIG_DIR/custom_components/note_to_self" ]; then
  say "Backing up existing custom component..."
  mv "$CONFIG_DIR/custom_components/note_to_self" "$CONFIG_DIR/custom_components/note_to_self.backup-$STAMP"
fi
if [ -d "$CONFIG_DIR/www/note-to-self" ]; then
  say "Backing up existing frontend assets..."
  mv "$CONFIG_DIR/www/note-to-self" "$CONFIG_DIR/www/note-to-self.backup-$STAMP"
fi

cp -R "$SRC/custom_components/note_to_self" "$CONFIG_DIR/custom_components/note_to_self"
cp -R "$SRC/www/note-to-self" "$CONFIG_DIR/www/note-to-self"

say ""
say "Installed FailureNTS™ v$VERSION."
say "Next steps:"
say "1. Restart Home Assistant."
say "2. Go to Settings -> Devices & Services -> Add Integration."
say "3. Add Note to self."
say "4. Open Note to self from the sidebar and hard-refresh the browser."
say ""
say "Existing notes/uploads were not touched."
