#!/usr/bin/env bash
# Publish a static site directory with curl and jq; no InstaHost CLI needed. The steps:
#   1. walk the directory, skipping dot-prefixed files and folders, and record each file's
#      path, size and MD5;
#   2. POST /v1/artifacts with that manifest; the answer carries the first batch of upload URLs;
#   3. PUT every file, asking /uploads for the next batch of URLs just before using it;
#   4. POST the complete_url to publish.
# The directory needs an index.html at its root, and its pages must use relative URLs
# ("css/site.css", not "/css/site.css"): sites are served under /<id>/. File names must not
# contain newlines. Use the CLI for retries, exclusions of credentials and larger sites.
# Usage: INSTAHOST_API_URL=https://<api-host> ./publish.sh <dir> [ttl-seconds]
# Prints {url, expires_at, id, delete_token} as JSON. Keep the delete token: it is shown once.
set -euo pipefail

api="${INSTAHOST_API_URL:?Set INSTAHOST_API_URL to the API origin, for example https://instahost.dev}"
dir="${1:?Usage: publish.sh <dir> [ttl-seconds]}"
ttl="${2:-86400}"
[ -f "$dir/index.html" ] || { echo "publish.sh: $dir has no index.html at its root" >&2; exit 3; }
cd "$dir"

md5_hex() { if command -v md5sum >/dev/null 2>&1; then md5sum "$1" | cut -d' ' -f1; else md5 -q "$1"; fi; }

# request METHOD URL [curl options...]: prints the response body; on HTTP >= 400 prints the
# status and body (the API's error envelope, or the storage error) on stderr and fails.
request() {
  local body status
  body="$(mktemp)"
  status="$(curl -sS -o "$body" -w '%{http_code}' -X "$1" "${@:3}" "$2")" || { rm -f "$body"; return 7; }
  if [ "$status" -ge 400 ]; then echo "publish.sh: $1 answered HTTP $status: $(cat "$body")" >&2; rm -f "$body"; return 1; fi
  cat "$body"
  rm -f "$body"
}

manifest="$(find . -type f ! -path '*/.*' | LC_ALL=C sort | while IFS= read -r f; do
  jq -n --arg path "${f#./}" --argjson size "$(wc -c < "$f" | tr -d ' ')" --arg md5 "$(md5_hex "$f")" \
    '{path: $path, size: $size, md5: $md5}'
done | jq -s .)"

created="$(jq -n --argjson files "$manifest" --argjson ttl "$ttl" '{type: "site", ttl_seconds: $ttl, files: $files}' |
  request POST "$api/v1/artifacts" -H 'content-type: application/json' --data-binary @-)"
token="$(jq -r .delete_token <<<"$created")"

# PUTs one batch of upload instructions ({files: [{path, url, headers}]}), replaying the signed headers.
put_batch() {
  local count i path url header headers
  count="$(jq '.files | length' <<<"$1")"
  for ((i = 0; i < count; i++)); do
    path="$(jq -r ".files[$i].path" <<<"$1")"
    url="$(jq -r ".files[$i].url" <<<"$1")"
    headers=()
    while IFS= read -r header; do headers+=(-H "$header"); done \
      < <(jq -r ".files[$i].headers | to_entries[] | \"\(.key): \(.value)\"" <<<"$1")
    request PUT "$url" --globoff -H 'Expect:' "${headers[@]}" -T "./$path" >/dev/null
  done
}

put_batch "$(jq .upload <<<"$created")"
remaining="$(jq -c --argjson first "$(jq '[.upload.files[].path]' <<<"$created")" '[.[].path] - $first' <<<"$manifest")"
batch_size="$(jq -r .upload.batch_size <<<"$created")"
while [ "$(jq length <<<"$remaining")" -gt 0 ]; do
  paths="$(jq -c --argjson n "$batch_size" '.[:$n]' <<<"$remaining")"
  remaining="$(jq -c --argjson n "$batch_size" '.[$n:]' <<<"$remaining")"
  # Assigned first, so that a failed /uploads stops the script (set -e) before anything else.
  batch="$(jq -n --argjson paths "$paths" '{paths: $paths}' |
    request POST "$(jq -r .upload.uploads_url <<<"$created")" -H 'content-type: application/json' \
      -H "authorization: Bearer $token" --data-binary @-)"
  put_batch "$(jq .upload <<<"$batch")"
done

published="$(request POST "$(jq -r .upload.complete_url <<<"$created")" -H "authorization: Bearer $token")"
jq --arg token "$token" '{url: .artifact.url, expires_at: .artifact.expires_at, id: .artifact.id, delete_token: $token}' <<<"$published"
