#!/usr/bin/env bash
# Install/update Myoshi for the current user. No sudo; HTTPS verification stays enabled.
set -euo pipefail
portal='https://playmyoshi.com'
fail() { printf 'Myoshi: %s\n' "$*" >&2; exit 1; }
[ "$(uname -s)" = Linux ] || fail 'This installer is for Linux. Download the Windows client from https://playmyoshi.com/.'
case "$(uname -m)" in x86_64|amd64) ;; *) fail 'The current Linux client requires an x64 PC.' ;; esac
for dependency in curl tar gzip sha256sum awk mktemp; do command -v "$dependency" >/dev/null || fail "Install the required command: $dependency"; done
[ -n "${HOME:-}" ] && [[ "$HOME" = /* ]] || fail 'A valid home directory is required.'
install_root="${XDG_DATA_HOME:-$HOME/.local/share}/myoshi"
[[ "$install_root" = /* ]] || fail 'XDG_DATA_HOME must be an absolute path.'
bin_dir="$HOME/.local/bin"
mkdir -p "$install_root/releases" "$bin_dir"
staging=$(mktemp -d "$install_root/.download.XXXXXXXX")
trap 'rm -rf -- "$staging"' EXIT
printf 'Checking the latest Myoshi Linux release…\n'
curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL --retry 2 "$portal/downloads/linux/latest.txt" -o "$staging/release.txt" || fail 'Could not check the release. For the private VM, trust the development CA and check /etc/hosts first.'
mapfile -t release < "$staging/release.txt"
[ "${#release[@]}" -eq 3 ] || fail 'Invalid release metadata.'
release_version=${release[0]}; release_sha=${release[1]}; release_url=${release[2]}
[[ "$release_version" =~ ^[A-Za-z0-9._-]{1,64}$ ]] || fail 'Invalid release version.'
[[ "$release_sha" =~ ^[a-f0-9]{64}$ ]] || fail 'Invalid release checksum.'
[ "$release_url" = "/releases/myoshi-linux-x64-$release_sha.tar.gz" ] || fail 'Invalid release archive location.'
printf 'Downloading Myoshi %s…\n' "$release_version"
curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fL --retry 2 "$portal$release_url" -o "$staging/client.tar.gz" || fail 'Download failed. The existing client was not changed.'
printf '%s  %s\n' "$release_sha" "$staging/client.tar.gz" | sha256sum --check --status || fail 'Download checksum mismatch. The existing client was not changed.'
tar -tzf "$staging/client.tar.gz" > "$staging/contents.txt" || fail 'The archive is damaged.'
while IFS= read -r member; do
 case "$member" in myoshi-account-linux-x64/|myoshi-account-linux-x64/*) ;; *) fail 'Unexpected archive path.' ;; esac
 case "/$member/" in */../*|*/./*) fail 'Unsafe archive path.' ;; esac
done < "$staging/contents.txt"
# Releases contain regular files/directories only, never links or special files.
tar -tvzf "$staging/client.tar.gz" | awk 'substr($0,1,1)!="-" && substr($0,1,1)!="d" {bad=1} END {exit bad}' || fail 'Unsupported archive entry type.'
mkdir "$staging/unpack"
tar -xzf "$staging/client.tar.gz" --no-same-owner --no-same-permissions -C "$staging/unpack"
package="$staging/unpack/myoshi-account-linux-x64"
[ -f "$package/run-client.sh" ] && [ -f "$package/myoshi-client" ] && [ -f "$package/SHA256SUMS" ] || fail 'The client archive is incomplete.'
(cd "$package" && sha256sum --check --quiet SHA256SUMS) || fail 'Client file verification failed. The existing client was not changed.'
chmod u+x "$package/run-client.sh" "$package/myoshi-client"
release_dir="$install_root/releases/$release_sha"
current_target=$(readlink "$install_root/current" 2>/dev/null || true)
if [[ "$current_target" == "$install_root/releases/$release_sha" || "$current_target" == "$install_root/releases/$release_sha-repair-"* ]] && [ "$(dirname "$current_target")" = "$install_root/releases" ]; then release_dir=$current_target; fi
if [ -e "$release_dir" ]; then
  # Verify cached files against the freshly downloaded manifest, never a cached one.
  if ! (cd "$release_dir" && sha256sum --check --quiet "$package/SHA256SUMS"); then
    printf 'Installing a clean copy of the modified cached release…\n'
    repair_id=${staging##*/}; release_dir="$install_root/releases/$release_sha-repair-${repair_id#.download.}"
    mv -- "$package" "$release_dir"
  fi
else
  mv -- "$package" "$release_dir"
fi
[ -x "$release_dir/run-client.sh" ] && [ -x "$release_dir/myoshi-client" ] || fail 'The client release is incomplete.'
ln -s "$release_dir" "$staging/current"
mv -Tf -- "$staging/current" "$install_root/current"
printf '#!/usr/bin/env bash\nexec %q "$@"\n' "$install_root/current/run-client.sh" > "$staging/myoshi"
chmod u+x "$staging/myoshi"
mv -f -- "$staging/myoshi" "$bin_dir/myoshi"
mkdir -p "${XDG_DATA_HOME:-$HOME/.local/share}/applications" "$install_root"
cat > "$install_root/icon.svg" <<'SVG'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><defs><linearGradient id="g" x2="1" y2="1"><stop stop-color="#8ce7ec"/><stop offset="1" stop-color="#c5a4ff"/></linearGradient></defs><rect x="4" y="4" width="120" height="120" rx="28" fill="#101425" stroke="#605777" stroke-width="3"/><path d="M30 91V40h13l21 29 21-29h13v51H83V63L64 89 45 63v28Z" fill="url(#g)"/><path d="m107 11 3 8 8 3-8 3-3 8-3-8-8-3 8-3Z" fill="#91eef0"/></svg>
SVG
# Desktop fields quote spaces and escape literal field-code percent signs.
desktop_exec=${bin_dir//\\/\\\\}; desktop_exec=${desktop_exec//\"/\\\"}; desktop_exec=${desktop_exec//%/%%}
desktop_icon=${install_root//\\/\\\\}
cat > "$staging/myoshi.desktop" <<DESKTOP
[Desktop Entry]
Type=Application
Name=Myoshi
Comment=Enter Neo Tokyo with your character and Oshi
Exec="$desktop_exec/myoshi"
Icon=$desktop_icon/icon.svg
Terminal=false
Categories=Game;
StartupNotify=true
DESKTOP
mv -f -- "$staging/myoshi.desktop" "${XDG_DATA_HOME:-$HOME/.local/share}/applications/myoshi.desktop"
printf '\nMyoshi %s is installed.\nLaunch Myoshi from your applications menu, or run:\n\n  %q\n\nRun this installer again to update. Your account credentials stay in the OS credential store.\n' "$release_version" "$bin_dir/myoshi"
