#! /bin/bash
set -e

[[ $0 != 'tool/refresh.sh' ]] && echo "Must be run as tool/refresh.sh" && exit

dart pub get

temp=$(mktemp -d -t tzdata-XXXXXXXXXX)

pushd $temp > /dev/null

echo "Fetching latest database..."
curl https://data.iana.org/time-zones/tzdata-latest.tar.gz | tar -zx

tz_version=$(cat version)
echo "Detected timezone database version: $tz_version"

echo "Compiling into zoneinfo files..."
mkdir zoneinfo
make rearguard.zi

echo "Generating lib/src/common_locations.dart..."

# Path to the file in your project root
target_file="$OLDPWD/lib/src/common_locations.dart"

# Create/Overwrite the file with the header
cat <<EOF > "$target_file"
// Copyright (c) 2014, the timezone project authors. Please see the AUTHORS
// file for details. All rights reserved. Use of this source code is governed
// by a BSD-style license that can be found in the LICENSE file.

// Generated by tool/refresh.sh. Do not edit manually.
// Timezone data version: $tz_version
const List<String> commonLocations = [
EOF

# Extract 'Zone' lines, take the ID (column 2), wrap in quotes, and sort
awk '/^Zone/ { print "  \x27" $2 "\x27," }' rearguard.zi | sort -u >> "$target_file"

# Close the Set
echo "];" >> "$target_file"

echo "Canonical set saved to $target_file"

zic -d zoneinfo -b fat rearguard.zi

popd > /dev/null

mkdir -p lib/data

# Pass the zoneinfo directory to the encoding script
dart tool/encode_tzf.dart --zoneinfo $temp/zoneinfo

rm -r $temp

# Create the source embeddings
for scope in latest latest_all latest_10y; do
  echo "Creating embedding: $scope..."
  dart tool/encode_dart.dart lib/data/$scope.{tzf,dart} $tz_version
done

dart format lib/data

if [[ -n "$GITHUB_OUTPUT" ]]; then
  echo "tz_version=$tz_version" >> "$GITHUB_OUTPUT"
fi
