#!/usr/bin/env bash
# YouTube upload walkthrough with curl (APIWings, free to use, MIT licence).
# The seven steps of an upload: OAuth code exchange, resumable session, file, status check if it
# fails, video ID, processing status, thumbnail. Needs bash, curl and python3 (to read JSON).
#
# Try it without any Google account against the local mock:
#   node youtube-mock-server.mjs 8080 &
#   YT_API=http://127.0.0.1:8080 TOKEN_URL=http://127.0.0.1:8080/token CODE=test-code \
#     VIDEO=my-test.mp4 THUMB=my-thumb.jpg bash youtube-upload-walkthrough.sh
# Against YouTube: set CLIENT_ID, CLIENT_SECRET, REDIRECT_URI and the CODE from step 1, and leave
# YT_API and TOKEN_URL unset. Use a test channel and keep PRIVACY=private until you trust it.
set -euo pipefail

YT_API="${YT_API:-https://www.googleapis.com}"
TOKEN_URL="${TOKEN_URL:-https://oauth2.googleapis.com/token}"
VIDEO="${VIDEO:?Set VIDEO to the path of a video file}"
TITLE="${TITLE:-Test upload}"
PRIVACY="${PRIVACY:-private}"
SCOPES="https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtube.readonly"
json() { python3 -c "import json,sys; d=json.load(sys.stdin); print(eval(sys.argv[1], {'d': d}))" "$1"; }

# 1. OAuth: send the user to Google's consent screen, then exchange the code for tokens.
if [ -z "${CODE:-}" ]; then
  q=$(python3 -c "import urllib.parse,sys; print(urllib.parse.urlencode({'client_id':sys.argv[1],'redirect_uri':sys.argv[2],'response_type':'code','scope':sys.argv[3],'access_type':'offline','include_granted_scopes':'true','state':'random-state-value'}))" "${CLIENT_ID:?}" "${REDIRECT_URI:?}" "$SCOPES")
  echo "Open this URL, approve, and run again with CODE=<the code parameter of the redirect>:"
  echo "https://accounts.google.com/o/oauth2/v2/auth?$q"
  exit 0
fi
TOKENS=$(curl -sS -X POST "$TOKEN_URL" \
  --data-urlencode "code=$CODE" --data-urlencode "client_id=${CLIENT_ID:-test-client}" \
  --data-urlencode "client_secret=${CLIENT_SECRET:-test-secret}" \
  --data-urlencode "redirect_uri=${REDIRECT_URI:-http://localhost/callback}" \
  --data-urlencode "grant_type=authorization_code")
ACCESS_TOKEN=$(echo "$TOKENS" | json "d['access_token']")
echo "1. Access token received (store the refresh_token too, encrypted)."

# 2. Open a resumable session: metadata as JSON, file size and type in headers. Location = session URI.
SIZE=$(wc -c < "$VIDEO" | tr -d ' ')
META=$(python3 -c "import json,sys; print(json.dumps({'snippet':{'title':sys.argv[1],'categoryId':'22'},'status':{'privacyStatus':sys.argv[2],'selfDeclaredMadeForKids':False},'paidProductPlacementDetails':{'hasPaidProductPlacement':False}}))" "$TITLE" "$PRIVACY")
SESSION=$(curl -sS -D - -o /dev/null -X POST \
  "$YT_API/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,paidProductPlacementDetails" \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json; charset=UTF-8" \
  -H "X-Upload-Content-Length: $SIZE" -H "X-Upload-Content-Type: video/mp4" --data "$META" \
  | tr -d '\r' | sed -n 's/^[Ll]ocation: //p')
[ -n "$SESSION" ] || { echo "No session URI: check the token, the quota and the metadata."; exit 1; }
echo "2. Session opened. Save this URI to resume later: $SESSION"

# 3. Send the file. 4. If the answer is lost or 5xx, ask the session how many bytes it has and resume.
OUT=$(mktemp)
put_from() { # $1 = first byte to send
  tail -c +"$(( $1 + 1 ))" "$VIDEO" | curl -sS -o "$OUT" -w '%{http_code}' -X PUT "$SESSION" \
    -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: video/mp4" -H "Expect:" \
    -H "Content-Range: bytes $1-$(( SIZE - 1 ))/$SIZE" --data-binary @- 2>/dev/null || true
}
CODE_HTTP=$(put_from 0); CODE_HTTP=${CODE_HTTP:-000}
TRIES=0
while [ "$CODE_HTTP" != "200" ] && [ "$CODE_HTTP" != "201" ]; do
  case "$CODE_HTTP" in 000|1??|500|502|503|504) ;; *) echo "Upload failed with $CODE_HTTP: $(cat "$OUT")"; exit 1 ;; esac
  TRIES=$((TRIES + 1)); [ "$TRIES" -le 5 ] || { echo "Giving up; resume later with $SESSION"; exit 1; }
  sleep "$TRIES"
  STATUS=$(curl -sS -D - -o "$OUT" -w '%{http_code}' -X PUT "$SESSION" \
    -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Length: 0" -H "Content-Range: bytes */$SIZE" | tr -d '\r')
  HTTP=$(echo "$STATUS" | tail -n 1)
  echo "4. Status check: HTTP $HTTP"
  if [ "$HTTP" = "200" ] || [ "$HTTP" = "201" ]; then CODE_HTTP=$HTTP; break; fi    # finished already: no re-upload
  if [ "$HTTP" = "404" ]; then echo "Session expired. If the last bytes may have arrived, check the channel's uploads before starting again."; exit 1; fi
  RANGE_END=$(echo "$STATUS" | sed -n 's/^[Rr]ange: bytes=0-//p')
  NEXT=$(( ${RANGE_END:--1} + 1 ))
  echo "   YouTube has $NEXT of $SIZE bytes; resuming from byte $NEXT."
  CODE_HTTP=$(put_from "$NEXT"); CODE_HTTP=${CODE_HTTP:-000}
done
echo "3. Upload finished (HTTP $CODE_HTTP)."

# 5. The response is the video resource: keep its ID.
VIDEO_ID=$(json "d['id']" < "$OUT")
echo "5. Video ID: $VIDEO_ID  https://www.youtube.com/watch?v=$VIDEO_ID  (privacy applied: $(json "d['status'].get('privacyStatus','?')" < "$OUT"))"

# 6. Processing status (owner only; 1 quota unit per call).
STATE=processing
for i in 1 2 3 4 5 6 7 8 9 10; do
  STATE=$(curl -sS "$YT_API/youtube/v3/videos?part=status,processingDetails&id=$VIDEO_ID" \
    -H "Authorization: Bearer $ACCESS_TOKEN" | json "(d.get('items') or [{}])[0].get('processingDetails',{}).get('processingStatus','processing')")
  echo "6. Processing: $STATE"
  [ "$STATE" = "processing" ] || break
  sleep "${POLL_SECONDS:-10}"
done

# 7. Custom thumbnail (50 quota units; needs a verified account). For Shorts, only after processing succeeded.
if [ -n "${THUMB:-}" ] && [ "$STATE" = "succeeded" ]; then
  TYPE=image/jpeg; case "$THUMB" in *.png|*.PNG) TYPE=image/png ;; esac
  T=$(curl -sS -o "$OUT" -w '%{http_code}' -X POST "$YT_API/upload/youtube/v3/thumbnails/set?videoId=$VIDEO_ID&uploadType=media" \
    -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: $TYPE" --data-binary @"$THUMB")
  echo "7. Thumbnail: HTTP $T"
fi
rm -f "$OUT"
