// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

import 'dart:io';

import 'package:crypto/crypto.dart' show sha256;

Future<void> main(List<String> args) async {
  final version = args[0];

  final httpClient = HttpClient();

  print('Checking hashes for $version');
  final fileHashes = <(String, String), String>{};
  for (final rustTarget in [
    'armv7-linux-androideabi',
    'aarch64-linux-android',
    'i686-linux-android',
    // 'riscv64-linux-android',
    'x86_64-linux-android',
    // 'aarch64-unknown-fuchsia',
    // 'x86_64-unknown-fuchsia',
    'aarch64-apple-ios',
    'x86_64-apple-ios',
    'armv7-unknown-linux-gnueabihf',
    'aarch64-unknown-linux-gnu',
    // 'i686-unknown-linux-gnu',
    // 'riscv32gc-unknown-linux-gnu',
    'riscv64gc-unknown-linux-gnu',
    'x86_64-unknown-linux-gnu',
    'aarch64-apple-darwin',
    'x86_64-apple-darwin',
    'aarch64-pc-windows-msvc',
    'i686-pc-windows-msvc',
    'x86_64-pc-windows-msvc',
  ]) {
    for (final libraryType in [
      'dynamic-with_data',
      'static',
      'static-with_data',
    ]) {
      print('Checking hash for $rustTarget');
      final uri = Uri.parse(
        'https://github.com/unicode-org/icu4x/releases/'
        'download/$version/icu4x-2-$libraryType-$rustTarget',
      );
      print('Fetch file from $uri');
      final request = await httpClient.getUrl(uri);
      final response = await request.close();
      if (response.statusCode != 200) {
        print('File not found at $uri');
        continue;
      }
      final bytes = await response.fold<List<int>>([], (a, b) => a..addAll(b));

      final tempFile = File(
        '${Directory.systemTemp.path}/icu4x_verify_$rustTarget-$libraryType',
      );
      await tempFile.writeAsBytes(bytes);

      print(
        'Verifying GitHub artifact attestation for $rustTarget-$libraryType...',
      );
      final verifyResult = await Process.run('gh', [
        'attestation',
        'verify',
        tempFile.path,
        '--owner',
        'unicode-org',
        '--repo',
        'icu4x',
      ]);
      if (verifyResult.exitCode != 0) {
        throw Exception(
          'SECURITY ERROR: Artifact attestation verification failed for '
          '$rustTarget-$libraryType at $uri:\n${verifyResult.stderr}',
        );
      }

      final fileHash = sha256.convert(bytes).toString();
      fileHashes[(rustTarget, libraryType)] = fileHash;
      print('Hash is $fileHash');
    }
  }
  httpClient.close(force: true);

  await File('lib/src/hook_helpers/hashes.dart').writeAsString('''
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

// ignore_for_file: public_member_api_docs

// THIS FILE IS AUTOGENERATED BY `tool/regenerate_hashes.dart`. TO UPDATE, RUN
//
//    dart tool/regenerate_hashes.dart <github tag>
//

const version = '$version';

const fileHashes = <(String, String), String>{
${fileHashes.map((key, value) => MapEntry(("'${key.$1}'", "'${key.$2}'"), "'$value'")).entries.map((e) => '  ${e.key}:\n      ${e.value},').join('\n')}
};
''');
}
