#!/bin/bash
# OctoWoW installer / repair for Linux. Downloads the client file by file from the signed install list:
# every file resumes where it stopped after a dropped connection, is retried automatically and is
# SHA-256 checked. Run it again at any time - finished files are skipped.
#   ./octo-install.sh [target folder]      (default: ~/Games/OctoWoW)
#   ./octo-install.sh --repair [folder]    (re-check every file, replace damaged ones)
# Needs: bash, curl, openssl, sha256sum. With aria2c installed it downloads peer-to-peer first (OCTO_P2P=0 turns that off). Then play with ./play-linux.sh in the client folder.
set -u
URL="${OCTO_URL:-https://dl.hybridgateway.eu/octo/}"
REPAIR=0; [ "${1:-}" = "--repair" ] && { REPAIR=1; shift; }
DIR="${1:-$HOME/Games/OctoWoW}"
die() { echo "ERROR: $*" >&2; exit 1; }
for t in curl openssl sha256sum; do command -v $t >/dev/null || die "please install $t"; done
mkdir -p "$DIR/_patch" || die "cannot create $DIR"; cd "$DIR" || exit 1
W=_patch; PUB=$W/patch-manifest-public.pem
cat > "$PUB" <<'KEY'
-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAs5D7l0IvrIqoOxA4V3xc
DRx3ESM32jQYyBtG0RPPEAQLVvF8jwswJcmzMc7S55Jd5ZguL6Q4tTKgh6M4o1ko
9fZ1CpmPsyPFGniZdz+wc1mNihB/Zmdz2tt1bYl5H0SVx7NUgT1YB+pAw0UOlNpm
8nq/n/3u3mrvfzKFuffqEKezsCK3XX2dPz2OfRg3XrMmctGOPonVCCzNHSku6xRE
q/JwvtG9lgYWwYh2Wrjrk1jN4OA+V9m6/maKY0IRmK1kPJgvWn/y7jm1RbcDlQS7
xom2YQF3KpL9D88gLy9h+wxUGFQrcrs24f5kShIrlVVf31i8pMe7WJyNdsN26kSZ
KWnvCrHjuWWv/szyDHUNnzUlYUM6qI4q9IN6z+6ItD/d6fwLKpqO7mNoIybzDd2T
p/YRuaEQ5SeFjbyeq67AD8t9g4wCUxMsHa/mxTw8NSMnbR6HbSlj4EN8qzb9ZawL
hHgy5hKoKh/SRwuoBnm7vnqoahSjfn/SZCiN6Ee2j57TAgMBAAE=
-----END PUBLIC KEY-----
KEY
get() { curl -fsSL --retry 8 --retry-delay 3 --retry-all-errors --connect-timeout 30 "$1" -o "$2"; }
get "${URL}install.txt" $W/install.txt.new && get "${URL}install.txt.sig" $W/install.txt.sig.new || die "cannot reach $URL"
openssl dgst -sha256 -verify "$PUB" -signature $W/install.txt.sig.new $W/install.txt.new >/dev/null 2>&1 || die "install list signature is NOT valid - nothing installed"
mv $W/install.txt.new $W/install.txt; mv $W/install.txt.sig.new $W/install.txt.sig
head -1 $W/install.txt | grep -qx "OCTO-INSTALL 1" && tail -1 $W/install.txt | grep -qx END || die "unsupported install list"
REL=$(sed -n 's/^RELEASE //p' $W/install.txt); BASE=$(sed -n 's/^BASE //p' $W/install.txt)
case "$BASE" in *..*|"") die "bad install list";; esac
touch $W/verified.txt
# #16: a reused folder can still hold an older install's store files. The store reader takes the newest index
# generation per bucket, so leftover .idx files hide this release's indexes ("update base data missing from this
# client"). After an install the client is exactly this release, so keep only the listed store files.
prune_store() {
  [ -d Data/data ] || return 0
  local -A KEEP; local p f n=0
  while read -r p; do KEEP[$p]=1; done < <(grep '^F ' $W/install.txt | awk '$4 ~ /^Data\/data\// {print $4}')
  for f in Data/data/*.idx Data/data/data.[0-9][0-9][0-9] Data/data/*.lru Data/data/shmem; do
    [ -e "$f" ] && [ -z "${KEEP[$f]:-}" ] && { rm -f -- "$f"; n=$((n+1)); }
  done
  [ $n = 0 ] || echo "Removed $n leftover store file(s) of an older install"
}
enc() { local s="$1" o="" c i; for ((i=0;i<${#s};i++)); do c="${s:i:1}"; case "$c" in [A-Za-z0-9/._~-]) o+="$c";; *) printf -v c '%%%02X' "'$c"; o+="$c";; esac; done; printf '%s' "$o"; }
# work list: everything not already verified (or all files with --repair); .build.info last
mapfile -t LIST < <(grep '^F ' $W/install.txt | awk '{p=$0; sub(/^F [^ ]+ [^ ]+ /,"",p); print ($4==".build.info"?1:0) "\t" $2 "\t" $3 "\t" p}' | sort -s -t$'\t' -k1,1n | cut -f2-)
NEED=0; TODO=()
for e in "${LIST[@]}"; do
  IFS=$'\t' read -r sha size path <<<"$e"
  case "$path" in /*|*..*) die "bad path in install list: $path";; esac
  if [ -f "$path" ] && [ "$(stat -c %s "$path")" = "$size" ]; then
    if [ $REPAIR = 0 ] && grep -qxF "$size $sha $path" $W/verified.txt; then continue; fi
    if [ "$(sha256sum "$path" | cut -d' ' -f1)" = "$sha" ]; then grep -qxF "$size $sha $path" $W/verified.txt || echo "$size $sha $path" >> $W/verified.txt; continue; fi
    echo "  $path differs - will be replaced"
  fi
  TODO+=("$e"); NEED=$((NEED+size))
done
[ ${#TODO[@]} = 0 ] && { prune_store; echo "All client files of release $REL are complete in $DIR"; exit 0; }
FREE=$(df -B1 --output=avail . | tail -1); [ "$FREE" -gt "$NEED" ] || echo "WARNING: $((NEED/1000000000)) GB to download but only $((FREE/1000000000)) GB free here"
# Peer-to-peer first (when aria2c is installed and much is missing): the signed install-p2p.txt names the release torrent,
# web-seeded from our server. aria2 writes files in place; .build.info is diverted. Everything is re-checked afterwards.
if [ "${OCTO_P2P:-1}" != 0 ] && command -v aria2c >/dev/null && [ "$NEED" -ge "${OCTO_P2P_MIN:-2000000000}" ] && \
   get "${URL}install-p2p.txt" $W/install-p2p.txt && get "${URL}install-p2p.txt.sig" $W/install-p2p.txt.sig && \
   openssl dgst -sha256 -verify "$PUB" -signature $W/install-p2p.txt.sig $W/install-p2p.txt >/dev/null 2>&1 && \
   grep -qx "RELEASE $REL" $W/install-p2p.txt; then
  read -r _ TSHA TSIZE TURL < <(grep '^TORRENT ' $W/install-p2p.txt); case "$TURL" in *://*) ;; *) TURL="$URL$TURL";; esac
  mkdir -p $W/p2p/hold; T=$W/p2p/OctoWoW-$REL.torrent
  { [ -f "$T" ] && [ "$(sha256sum "$T" | cut -d' ' -f1)" = "$TSHA" ]; } || get "$TURL" "$T"
  if [ "$(sha256sum "$T" | cut -d' ' -f1)" = "$TSHA" ]; then
    declare -A WANT; for e in "${TODO[@]}"; do IFS=$'\t' read -r _ _ p <<<"$e"; WANT["$p"]=1; done
    { echo "$T"; i=0; SEL=""
      while IFS= read -r l; do i=$((i+1)); p="${l#F }"; p="${p#* }"; p="${p#* }"
        if [ "$p" = .build.info ]; then echo "  index-out=$i=$W/p2p/hold/$i"; else echo "  index-out=$i=$p"; [ -n "${WANT[$p]:-}" ] && SEL="$SEL,$i"; fi
      done < <(grep '^F ' $W/install.txt)
      echo "  select-file=${SEL#,}"; } > $W/p2p/aria2-input.txt
    CI=true; ls ./*.aria2 >/dev/null 2>&1 && CI=false
    echo "Downloading peer-to-peer (torrent; our server seeds it too). Ctrl+C stops; running this again continues."
    aria2c --input-file=$W/p2p/aria2-input.txt --dir=. --seed-time="${OCTO_SEED_MINUTES:-0}" --file-allocation=trunc \
      --allow-overwrite=true --auto-file-renaming=false --bt-save-metadata=false --check-integrity=$CI --auto-save-interval=30 \
      --bt-stop-timeout=300 --summary-interval=0 --console-log-level=error --max-tries=0 --retry-wait=10 \
      --dht-file-path=$W/p2p/dht.dat --log=$W/p2p/aria2.log --log-level=notice && { rm -f ./*.aria2; rm -rf $W/p2p/hold; }
    echo "Checking what arrived..."; LEFT=(); NEED=0
    for e in "${TODO[@]}"; do IFS=$'\t' read -r sha size path <<<"$e"
      if [ "$path" != .build.info ] && [ -f "$path" ] && [ "$(stat -c %s "$path")" = "$size" ] && [ "$(sha256sum "$path" | cut -d' ' -f1)" = "$sha" ]; then
        echo "$size $sha $path" >> $W/verified.txt; continue; fi
      LEFT+=("$e"); NEED=$((NEED+size)); done
    TODO=("${LEFT[@]}")
  else echo "torrent download did not verify - using direct download"; fi
fi
echo "Installing OctoWoW release $REL into $DIR: ${#TODO[@]} files, $((NEED/1000000000)) GB."
echo "You can stop with Ctrl+C at any time; running this again continues where it stopped."
DONE=0; N=0
for e in "${TODO[@]}"; do
  IFS=$'\t' read -r sha size path <<<"$e"; N=$((N+1)); mkdir -p "$(dirname "$path")"; part="$path.part"; bad=0
  printf '[%d/%d] %s (%d MB, %d of %d GB done)\n' $N ${#TODO[@]} "$path" $((size>>20)) $((DONE/1000000000)) $((NEED/1000000000))
  while :; do
    have=0; [ -f "$part" ] && have=$(stat -c %s "$part"); [ "$have" -gt "$size" ] && { rm -f "$part"; have=0; }
    if [ "$have" -lt "$size" ]; then
      curl -fL --retry 20 --retry-delay 5 --retry-all-errors --connect-timeout 30 --speed-limit 1024 --speed-time 60 \
           -C - -o "$part" $([ "$size" -gt 67108864 ] && echo --progress-bar || echo -s) "${URL}${BASE}$(enc "$path")" \
        || { echo "  connection problem - continuing in 10 s"; sleep 10; continue; }
    fi
    [ "$(stat -c %s "$part")" = "$size" ] || { echo "  incomplete - continuing"; sleep 3; continue; }
    if [ "$(sha256sum "$part" | cut -d' ' -f1)" = "$sha" ]; then mv -f "$part" "$path"; echo "$size $sha $path" >> $W/verified.txt; break; fi
    rm -f "$part"; bad=$((bad+1)); [ $bad -ge 3 ] && die "$path arrived damaged three times"; echo "  damaged in transfer - downloading again"
  done
  DONE=$((DONE+size))
done
chmod +x play-linux.sh 2>/dev/null
prune_store
echo; echo "OctoWoW release $REL installed in $DIR"; echo "Start the game with: $DIR/play-linux.sh"
