#!/bin/bash
# aiar: AI Archive - Self-extracting script generated by aiar-py. #
#
# Note to LLMs: this archive contains multiple files with separator lines. #
# Text files are contained between separators verbatim, binary files are base64-encoded. #
# If line 2 reads "aiar-set: <id> part N of M", this file is one part of a set of M #
# files; the lines after it say what it holds, and the other parts have the same <id>. #
# Every line in the extractor shell script ends with a '#' character to guard against a #
# possible CRLF line ending that would otherwise cause script failure in cases where CRLF #
# line endings are not supported. Choose a random SEPARATOR string to avoid conflicts when #
# archiving archives. #
#
SEPARATOR="++++++++++--------:11111111-2222-4333-8444-555555555555:" #
LC_ALL=C #
writing=false #
#
# Function to report errors and exit cleanly #
handle_error() { #
  echo "Error: $1" >&2 #
  exit 1 #
} #
#
usage() { #
  printf '%s\n' "usage: ${0##*/} [--this-part | --partial] [-h]" "" "Extracts the files in this aiar archive under the current directory. When it" "is one part of a set, the other parts are found beside it and the whole set" "is extracted." "" "  --this-part  extract only this file" "  --partial    when parts are missing, extract the ones present (status 3)" "  -h, --help   show this help" #
} #
#
this_part=false #
partial=false #
for arg in "$@"; do #
  case "$arg" in #
    --this-part) this_part=true ;; #
    --partial) partial=true ;; #
    -h|--help) usage; exit 0 ;; #
    *) echo "Error: unknown argument '$arg'" >&2; usage >&2; exit 2 ;; #
  esac #
done #
if [ "$this_part" = true ] && [ "$partial" = true ]; then #
  echo "Error: --this-part and --partial cannot be used together" >&2 #
  usage >&2 #
  exit 2 #
fi #
#
# Function to close the previous file descriptor and wait for bg processes #
close_previous_fd() { #
    if [ "$writing" = true ]; then #
      exec 3>&- #
        # Wait for any background process (like base64) to finish #
        wait 2>/dev/null || true #
    fi #
      writing=false #
} #
#
# Extract the records of file $1, whose separator is $2. The file is read as data only. #
extract_file() { #
  local sep="$2" line payload type filepath #
  writing=false #
  # IFS= preserves leading/trailing whitespace; the || test handles a final line without newline #
  while IFS= read -r line || [ -n "$line" ]; do #
    if [[ "$line" == "$sep"* ]]; then #
      close_previous_fd #
#
      payload="${line#$sep}" #
      IFS=':' read -r type filepath <<< "$payload" #
      # Strip any trailing carriage returns (DOS line endings) #
      filepath="${filepath%$'\r'}" #
#
      if [ -n "$filepath" -a ! -e "$filepath" ]; then #
        echo "Creating: $filepath" #
        mkdir -p "$(dirname "$filepath")" || handle_error "Cannot create directory for '$filepath'." #
#
        if [ "$type" == "t" ]; then #
          exec 3>"$filepath" || handle_error "Cannot open '$filepath' for writing." #
          writing=true #
      elif [ "$type" == "b" ]; then #
        # Use process substitution to pipe output to base64 decoder #
        # Wrap the entire pipeline in a single process that can be waited on #
        # Use sed to strip any trailing carriage returns from base64 input #
        exec 3> >( #
          error_file="$(mktemp)" #
          trap "rm -f \"$error_file\"" EXIT #
          sed 's/\r$//' | base64 -d > "$filepath" 2>"$error_file" #
          if [ -s "$error_file" ]; then #
            echo "Error: base64 decoding failed for '$filepath':" >&2 #
            cat "$error_file" >&2 #
            rm -f "$filepath" #
            exit 1 #
          fi #
        ) || handle_error "Cannot start base64 process for '$filepath'." #
        writing=true #
#
        else #
          handle_error "Invalid file type '$type' in separator." #
        fi #
      else #
          echo "Skipping already existing file: '$filepath'" #
      fi #
    elif [ "$writing" = true ]; then #
      printf '%s\n' "$line" >&3 #
    fi #
  done < "$1" #
  close_previous_fd #
} #
#
# The separator a part defines, from its SEPARATOR= line. #
part_separator() { #
  local line #
  while IFS= read -r line; do #
    line="${line%$'\r'}" #
    case "$line" in #
      SEPARATOR=\"*\"*) line="${line#SEPARATOR=\"}"; printf '%s' "${line%%\"*}"; return 0 ;; #
    esac #
  done < <(head -c 65536 < "$1") #
  return 1 #
} #
#
# Recognise line 2 of file $1. Sets rs_status (part, none, malformed or utf16) #
# and, for a part, rs_id, rs_n, rs_m and rs_fmt. #
read_set_line() { #
  local first="" second="" bom re n m prefix tail #
  rs_status=none #
  bom=$(head -c 2 < "$1" | od -An -tx1 | tr -d ' \n') #
  if [ "$bom" = "fffe" ] || [ "$bom" = "feff" ]; then #
    rs_status=utf16 #
    return 0 #
  fi #
  { IFS= read -r first; IFS= read -r second; } < <(head -c 4096 < "$1") #
  first="${first#$'\xef\xbb\xbf'}" #
  first="${first%$'\r'}" #
  second="${second%$'\r'}" #
  case "$second" in #
    "# aiar-set: "*|"// aiar-set: "*) ;; #
    *) return 0 ;; #
  esac #
  case "$first" in #
    "#!/bin/bash") rs_fmt=bash ;; #
    "#!/usr/bin/env node") rs_fmt=nodejs ;; #
    "#Requires -Version "*) rs_fmt=powershell ;; #
    SEPARATOR=\"*\") rs_fmt=bare ;; #
    ""|"# -*- coding: latin-1 -*-") rs_fmt=py ;; #
    *) rs_status=malformed; return 0 ;; #
  esac #
  prefix="# " #
  tail="" #
  [ "$rs_fmt" = nodejs ] && prefix="// " #
  [ "$rs_fmt" = bash ] && tail=" #" #
  re="^${prefix}aiar-set: ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}) part ([0-9]+) of ([0-9]+)${tail}\$" #
  if ! [[ "$second" =~ $re ]]; then #
    rs_status=malformed #
    return 0 #
  fi #
  rs_id="${BASH_REMATCH[1]}" #
  n="${BASH_REMATCH[2]}" #
  m="${BASH_REMATCH[3]}" #
  if [ "${#n}" -ne "${#m}" ] || [ "${m#0}" != "$m" ] || [ "${#m}" -gt 9 ]; then #
    rs_status=malformed #
    return 0 #
  fi #
  rs_n=$((10#$n)) #
  rs_m=$((10#$m)) #
  if [ "$rs_n" -lt 1 ] || [ "$rs_n" -gt "$rs_m" ] || [ "$rs_m" -lt 2 ]; then #
    rs_status=malformed #
    return 0 #
  fi #
  rs_status=part #
} #
#
# Part number $1 padded to the width of the part count. #
num() { #
  printf "%0${#own_m}d" "$1" #
} #
#
# The file name of part $2 of $3 for the -o name $1 (see "Part names"). #
part_name() { #
  local tag comps k i at lower #
  tag="$(printf "%0${#3}d" "$2")of$3" #
  IFS=. read -r -a comps <<< "$1" #
  k=$((${#comps[@]} - 1)) #
  i=$((k - 2)) #
  while [ "$i" -ge 0 ]; do #
    case "${comps[$((i + 1))]}" in #
      [Aa][Ii][Aa][Rr]) join_name "$((i + 1))" "$tag"; return 0 ;; #
    esac #
    i=$((i - 1)) #
  done #
  if [ "$k" -ge 1 ]; then #
    case "${comps[$k]}" in #
      [Aa][Ii][Aa][Rr]) join_name "$((k - 1))" "$tag"; return 0 ;; #
    esac #
  fi #
  at=$k #
  if [ "$k" -ge 1 ] && is_lang "${comps[$k]}"; then #
    at=$((k - 1)) #
  elif [ "$k" -ge 2 ] && is_txt "${comps[$k]}" && is_lang "${comps[$((k - 1))]}"; then #
    at=$((k - 2)) #
  elif [ "$k" -ge 1 ] && is_txt "${comps[$k]}"; then #
    at=$((k - 1)) #
  fi #
  join_name "$at" "aiar.$tag" #
} #
#
is_lang() { #
  case "$1" in #
    [Pp][Yy]|[Jj][Ss]|[Ss][Hh]|[Bb][Aa][Ss][Hh]|[Zz][Ss][Hh]|[Pp][Ss]1|[Pp][Ss][Mm]1) return 0 ;; #
  esac #
  return 1 #
} #
#
is_txt() { #
  case "$1" in #
    [Tt][Xx][Tt]) return 0 ;; #
  esac #
  return 1 #
} #
#
# The components of `comps` with $2 inserted after component $1. #
join_name() { #
  local out="${comps[0]}" j #
  j=1 #
  while [ "$j" -le "$1" ]; do #
    out="$out.${comps[$j]}" #
    j=$((j + 1)) #
  done #
  out="$out.$2" #
  while [ "$j" -lt "${#comps[@]}" ]; do #
    out="$out.${comps[$j]}" #
    j=$((j + 1)) #
  done #
  printf '%s' "$out" #
} #
#
# The -o name in the `aiar part` line (line 3) of file $1. #
output_name() { #
  local first second third re #
  { IFS= read -r first; IFS= read -r second; IFS= read -r third; } < <(head -c 65536 < "$1") #
  third="${third%$'\r'}" #
  re="^# aiar part ([0-9]+) of ([0-9]+) of (.*), limit ([0-9]+) bytes #\$" #
  if [[ "$third" =~ $re ]] && [ "$((10#${BASH_REMATCH[1]}))" -eq "$own_n" ] && [ "$((10#${BASH_REMATCH[2]}))" -eq "$own_m" ]; then #
    printf '%s' "${BASH_REMATCH[3]}" #
  fi #
} #
#
# The groups in file $1's `partial:` line that reach into a missing part. #
incomplete_in() { #
  local line body item name list piece a b k #
  while IFS= read -r line; do #
    line="${line%$'\r'}" #
    case "$line" in #
      "# partial: "*" #") ;; #
      *) continue ;; #
    esac #
    body="${line#\# partial: }" #
    body="${body% \#}" #
    while [ -n "$body" ]; do #
      case "$body" in #
        *") "*) item="${body%%) *}"; body="${body#*) }" ;; #
        *) item="${body%)}"; body="" ;; #
      esac #
      case "$item" in #
        *" (also in part"*) ;; #
        *) continue ;; #
      esac #
      name="${item% (also in part*}" #
      list="${item##*(also in part}" #
      list="${list#s}" #
      list="${list# }" #
      IFS=, read -r -a pieces <<< "$list" #
      for piece in "${pieces[@]}"; do #
        piece="${piece# }" #
        a="${piece%-*}" #
        b="${piece#*-}" #
        k=$((10#$a)) #
        while [ "$k" -le "$((10#$b))" ]; do #
          case " $missing " in #
            *" $k "*) case " $incomplete " in #
                *" $name "*) ;; #
                *) incomplete="$incomplete $name" ;; #
              esac ;; #
          esac #
          k=$((k + 1)) #
        done #
      done #
    done #
    return 0 #
  done < <(head -c 65536 < "$1") #
} #
#
read_set_line "$0" #
if [ "$rs_status" = malformed ]; then #
  echo "Error: ${0##*/}: malformed set line" >&2 #
  exit 1 #
fi #
if [ "$rs_status" != part ] || [ "$this_part" = true ]; then #
  extract_file "$0" "$SEPARATOR" #
  echo "Extraction complete." #
  exit 0 #
fi #
#
# This file is one part of a set: find the others beside it, as data only. #
own_id="$rs_id" #
own_n="$rs_n" #
own_m="$rs_m" #
own_fmt="$rs_fmt" #
self="${0##*/}" #
case "$0" in #
  */*) dir="${0%/*}"; [ -n "$dir" ] || dir=/ ;; #
  *) dir=. ;; #
esac #
case "$dir" in #
  -*) dir="./$dir" ;; #
esac #
part_file[$own_n]="$0" #
dup_count=0 #
errors=0 #
other_parts=0 #
other_sets=0 #
other_ids=" " #
shopt -s nullglob dotglob #
for f in "$dir"/*; do #
  name="${f##*/}" #
  [ "$name" = "$self" ] && continue #
  [ -L "$f" ] && continue #
  [ -f "$f" ] || continue #
  [ -r "$f" ] || continue #
  read_set_line "$f" #
  case "$rs_status" in #
    utf16) echo "$name: UTF-16, re-save as UTF-8 or use aiar extract" >&2; continue ;; #
    malformed) echo "$name: malformed set line, ignored" >&2; continue ;; #
    part) ;; #
    *) continue ;; #
  esac #
  if [ "$rs_id" != "$own_id" ]; then #
    other_parts=$((other_parts + 1)) #
    case "$other_ids" in #
      *" $rs_id "*) ;; #
      *) other_ids="$other_ids$rs_id "; other_sets=$((other_sets + 1)) ;; #
    esac #
    continue #
  fi #
  if [ "$rs_fmt" != "$own_fmt" ]; then #
    echo "Error: $name is a part of this set in another format" >&2 #
    errors=$((errors + 1)) #
    continue #
  fi #
  if [ "$rs_m" -ne "$own_m" ]; then #
    echo "Error: $name says this set has $rs_m parts, not $own_m" >&2 #
    errors=$((errors + 1)) #
    continue #
  fi #
  if [ -z "${part_file[$rs_n]}" ]; then #
    part_file[$rs_n]="$f" #
  else #
    dup_n[$dup_count]="$rs_n" #
    dup_file[$dup_count]="$f" #
    dup_count=$((dup_count + 1)) #
  fi #
done #
shopt -u nullglob dotglob #
#
n=1 #
while [ "$n" -le "$own_m" ]; do #
  i=0 #
  while [ "$i" -lt "$dup_count" ]; do #
    if [ "${dup_n[$i]}" -eq "$n" ]; then #
      a="${part_file[$n]}" #
      b="${dup_file[$i]}" #
      if cmp -s "$a" "$b"; then #
        echo "${a##*/} and ${b##*/} are identical copies of part $(num "$n"); using ${a##*/}" >&2 #
      else #
        echo "Error: ${a##*/} and ${b##*/} are different files for part $(num "$n")" >&2 #
        errors=$((errors + 1)) #
      fi #
    fi #
    i=$((i + 1)) #
  done #
  n=$((n + 1)) #
done #
#
if [ "$other_parts" -gt 0 ]; then #
  word_parts=parts #
  word_sets=sets #
  [ "$other_parts" -eq 1 ] && word_parts=part #
  [ "$other_sets" -eq 1 ] && word_sets=set #
  echo "ignored $other_parts $word_parts of $other_sets other $word_sets" >&2 #
fi #
#
missing="" #
missing_numbers="" #
expected="" #
oname="$(output_name "$0")" #
present=0 #
n=1 #
while [ "$n" -le "$own_m" ]; do #
  if [ -z "${part_file[$n]}" ]; then #
    missing="$missing $n" #
    missing_numbers="$missing_numbers, $(num "$n")" #
    [ -n "$oname" ] && expected="$expected, $(part_name "$oname" "$n" "$own_m")" #
  else #
    present=$((present + 1)) #
  fi #
  n=$((n + 1)) #
done #
if [ -n "$missing" ]; then #
  word=parts #
  [ "$present" -eq "$((own_m - 1))" ] && word=part #
  message="missing $word ${missing_numbers#, } of $own_m" #
  [ -n "$expected" ] && message="$message (expected ${expected#, })" #
  if [ "$partial" = true ]; then #
    echo "Warning: $message" >&2 #
  else #
    echo "Error: $message" >&2 #
    errors=$((errors + 1)) #
  fi #
fi #
if [ "$errors" -gt 0 ]; then #
  echo "Nothing was extracted." >&2 #
  exit 1 #
fi #
#
n=1 #
while [ "$n" -le "$own_m" ]; do #
  f="${part_file[$n]}" #
  if [ -n "$f" ]; then #
    if [ "$f" = "$0" ]; then #
      sep="$SEPARATOR" #
    else #
      sep="$(part_separator "$f")" || handle_error "No SEPARATOR in '${f##*/}'." #
    fi #
    extract_file "$f" "$sep" #
  fi #
  n=$((n + 1)) #
done #
#
if [ -n "$missing" ]; then #
  incomplete="" #
  n=1 #
  while [ "$n" -le "$own_m" ]; do #
    [ -n "${part_file[$n]}" ] && incomplete_in "${part_file[$n]}" #
    n=$((n + 1)) #
  done #
  [ -n "$incomplete" ] && echo "Warning: incomplete groups:$incomplete" >&2 #
  echo "Extraction incomplete: $present of $own_m parts." #
  exit 3 #
fi #
echo "Extraction complete." #
exit 0 #
#
# --- DATA --- #
#
++++++++++--------:11111111-2222-4333-8444-555555555555:b:assets/blob.bin
AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4
OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3Bx
cnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmq
q6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj
5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhsc
HR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RV
VldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2O
j5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbH
yMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8A
AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5
Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFy
c3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6Slpqeoqaqr
rK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk
5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/
++++++++++--------:11111111-2222-4333-8444-555555555555:t:empty.txt
++++++++++--------:11111111-2222-4333-8444-555555555555:t:readme.md
# Title

Some text.
++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/crlf.txt
line one
line two
++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/main.c
int main(void) {
    return 0;
}
++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/no_newline.txt
last line without newline
++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/utf8.txt
café   über
