#!/bin/bash
set -xeuo pipefail

mkdir -p /overlay/left4dead2/addons
cd /overlay/left4dead2/addons

for cmd in curl md5sum 7z; do
    command -v "$cmd" >/dev/null || { echo "Missing: $cmd" >&2; exit 1; }
done

CSV_URL="https://l4d2center.com/maps/servers/index.csv"
TEMP_CSV=$(mktemp)
trap 'rm -f "$TEMP_CSV"' EXIT
curl -fsSL -o "$TEMP_CSV" "$CSV_URL"

declare -A map_md5 map_links
{
    IFS= read -r _header
    while IFS=';' read -r Name _Size MD5 DownloadLink || [[ $Name ]]; do
        Name=$(echo "$Name" | xargs)
        MD5=$(echo "$MD5"  | xargs)
        DownloadLink=$(echo "$DownloadLink" | xargs)
        map_md5["$Name"]="$MD5"
        map_links["$Name"]="$DownloadLink"
    done
} < "$TEMP_CSV"

shopt -s nullglob
for file in *.vpk; do
    if [[ -z "${map_md5[$file]:-}" ]]; then
        rm -f "$file"
    elif [[ "$(md5sum "$file" | awk '{print $1}')" != "${map_md5[$file]}" ]]; then
        rm -f "$file"
    fi
done

for vpk in "${!map_md5[@]}"; do
    [[ -f "$vpk" ]] && continue
    url="${map_links[$vpk]}"
    [[ -n "$url" ]] || continue
    encoded=$(printf '%s' "$url" | sed 's/ /%20/g')
    TEMP_7Z=$(mktemp --suffix=.7z)
    curl -fsSL -o "$TEMP_7Z" "$encoded"
    7z x -y "$TEMP_7Z"
    rm -f "$TEMP_7Z"
done

echo "Synchronization complete."
