#!/usr/bin/env bash
# ==============================================================================
# Natrium Sovereign Encrypted Desktop Client — Linux Installer
# Website: https://natrium.sh / https://natrium.sh/downloads
# ==============================================================================
set -e

echo ""
echo "  _   _       _        _                 "
echo " | \ | | __ _| |_ _ __(_)_   _ _ __ ___  "
echo " |  \| |/ _\` | __| '__| | | | | '_ \` _ \ "
echo " | |\  | (_| | |_| |  | | |_| | | | | | |"
echo " |_| \_|\__,_|\__|_|  |_|\__,_|_| |_| |_|"
echo ""
echo "-> Natrium Email Desktop Installer (Linux Universal)"
echo ""

ARCH=$(uname -m)
case "$ARCH" in
  x86_64)
    ARCH_NAME="x86_64"
    DOWNLOAD_PLATFORM="linux"
    ;;
  aarch64|arm64)
    ARCH_NAME="arm64"
    DOWNLOAD_PLATFORM="linux_arm64"
    ;;
  *)
    echo "Error: Unsupported CPU architecture ($ARCH). Natrium requires x86_64 or aarch64."
    exit 1
    ;;
esac

TARGET_DIR="${HOME}/.local/bin"
DESKTOP_DIR="${HOME}/.local/share/applications"
ICON_DIR="${HOME}/.local/share/icons/hicolor/512x512/apps"

mkdir -p "$TARGET_DIR" "$DESKTOP_DIR" "$ICON_DIR"

APP_BINARY="${TARGET_DIR}/natrium-app"
LAUNCHER="${TARGET_DIR}/natrium"
ICON_PATH="${ICON_DIR}/natrium.png"
DESKTOP_FILE="${DESKTOP_DIR}/natrium.desktop"

CURRENT_VERSION="1.4.2"

echo "-> Downloading Natrium v${CURRENT_VERSION} ($ARCH_NAME)..."
if command -v curl >/dev/null 2>&1; then
  curl -sSL "https://natrium.sh/api/downloads?platform=${DOWNLOAD_PLATFORM}" -o "$APP_BINARY"
  curl -sSL "https://natrium.sh/app-icon-transparent-512.png" -o "$ICON_PATH"
elif command -v wget >/dev/null 2>&1; then
  wget -q "https://natrium.sh/api/downloads?platform=${DOWNLOAD_PLATFORM}" -O "$APP_BINARY"
  wget -q "https://natrium.sh/app-icon-transparent-512.png" -O "$ICON_PATH"
else
  echo "Error: Neither curl nor wget is available. Please install one to proceed."
  exit 1
fi

chmod +x "$APP_BINARY"

echo "-> Installing Natrium Email Launcher with Automatic Update Notifications..."
cat << 'LAUNCHER_EOF' > "$LAUNCHER"
#!/usr/bin/env bash
# Natrium Email Native Client Launcher & Auto-Update Daemon
CURRENT_VERSION="1.4.2"
APP_DIR="${HOME}/.local/bin"
APP_BINARY="${APP_DIR}/natrium-app"
UPDATE_ENDPOINT="https://natrium.sh/api/downloads/check-update"

check_updates_bg() {
  (
    sleep 3
    if command -v curl >/dev/null 2>&1; then
      RES=$(curl -sSL "${UPDATE_ENDPOINT}?platform=linux&currentVersion=${CURRENT_VERSION}" 2>/dev/null)
      if echo "$RES" | grep -q '"updateAvailable":true'; then
        NEW_VER=$(echo "$RES" | grep -o '"latestVersion":"[^"]*"' | cut -d'"' -f4)
        if command -v notify-send >/dev/null 2>&1; then
          notify-send -u normal -i natrium \
            "Natrium Email Update Available" \
            "Version ${NEW_VER} is ready. Visit https://natrium.sh/downloads or run 'natrium --update'."
        fi
      fi
    fi
  ) >/dev/null 2>&1 &
}

if [ "$1" = "--check-update" ]; then
  echo "Checking for updates..."
  if command -v curl >/dev/null 2>&1; then
    RES=$(curl -sSL "${UPDATE_ENDPOINT}?platform=linux&currentVersion=${CURRENT_VERSION}")
    echo "$RES"
  fi
  exit 0
fi

if [ "$1" = "--update" ]; then
  echo "Updating Natrium Email Desktop..."
  curl -fsSL https://natrium.sh/install.sh | bash
  exit 0
fi

if [ "$1" = "--version" ] || [ "$1" = "-v" ]; then
  echo "Natrium Email Desktop v${CURRENT_VERSION}"
  exit 0
fi

# Trigger non-blocking update check in background
check_updates_bg

# Launch main application
if [ -f "$APP_BINARY" ]; then
  exec "$APP_BINARY" "$@"
else
  echo "Error: Natrium Email binary not found at $APP_BINARY. Please re-run the installer."
  exit 1
fi
LAUNCHER_EOF

chmod +x "$LAUNCHER"

echo "-> Creating desktop launcher integration..."
cat <<EOF > "$DESKTOP_FILE"
[Desktop Entry]
Name=Natrium Email
Comment=Natrium Email Client
Exec=${LAUNCHER} %U
Terminal=false
Type=Application
Icon=natrium
Categories=Network;Email;Security;
MimeType=x-scheme-handler/mailto;
StartupWMClass=natrium
EOF

chmod +x "$DESKTOP_FILE"

echo ""
echo "✓ Installation Complete!"
echo "  Executable: $LAUNCHER"
echo "  Launcher:   $DESKTOP_FILE"
echo "  Version:    v${CURRENT_VERSION}"
echo ""
echo "Natrium Email desktop notifies you automatically whenever a new version is released."
echo "You can launch Natrium Email from your application menu or run: natrium"
echo ""
