#!/usr/bin/env bash
# Share one file with curl and jq; no InstaHost CLI needed. Three calls:
#   1. POST /v1/artifacts with the manifest: the file's name, size and MD5;
#   2. PUT the bytes to the presigned URL, replaying the returned (signed) headers exactly;
#   3. POST the complete_url to publish.
# Usage: INSTAHOST_API_URL=https://<api-host> ./share.sh <file> [ttl-seconds]
# Prints {url, expires_at, id, delete_token} as JSON. Keep the delete token: it is shown once.
# Unlike the CLI, this script does not refuse credential files: check what you share.
set -euo pipefail

api="${INSTAHOST_API_URL:?Set INSTAHOST_API_URL to the API origin, for example https://instahost.dev}"
file="${1:?Usage: share.sh <file> [ttl-seconds]}"
ttl="${2:-86400}"
[ -f "$file" ] && [ ! -L "$file" ] || { echo "share.sh: $file is not a regular file (symlinks are refused)" >&2; exit 3; }

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 "share.sh: $1 answered HTTP $status: $(cat "$body")" >&2; rm -f "$body"; return 1; fi
  cat "$body"
  rm -f "$body"
}

created="$(jq -n --arg path "$(basename "$file")" --argjson size "$(wc -c < "$file" | tr -d ' ')" \
    --arg md5 "$(md5_hex "$file")" --argjson ttl "$ttl" \
    '{type: "file", ttl_seconds: $ttl, files: [{path: $path, size: $size, md5: $md5}]}' |
  request POST "$api/v1/artifacts" -H 'content-type: application/json' --data-binary @-)"

# Every returned header is signed. 'Expect:' stops curl from adding "Expect: 100-continue".
headers=()
while IFS= read -r header; do headers+=(-H "$header"); done \
  < <(jq -r '.upload.files[0].headers | to_entries[] | "\(.key): \(.value)"' <<<"$created")
request PUT "$(jq -r '.upload.files[0].url' <<<"$created")" --globoff -H 'Expect:' "${headers[@]}" -T "$file" >/dev/null

token="$(jq -r .delete_token <<<"$created")"
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"
