csm-rs 0.90.0

A library for Shasta
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
use crate::bos::template::http_client::v2::types::BosSessionTemplate;
use crate::cfs::configuration::http_client::v3::types::{
  cfs_configuration_request::CfsConfigurationRequest,
  cfs_configuration_response::CfsConfigurationResponse,
};
use crate::hsm::group::http_client::{create_new_group, delete_group};
use crate::hsm::group::types::Group;
use crate::ims::image::{
  http_client::{
    patch,
    types::{Image, Link},
  },
  utils::get_by_name,
  utils::get_fuzzy,
};
use crate::ims::s3_client::BAR_FORMAT;
use crate::{bos, cfs, ims};
use chrono::Local;
use humansize::DECIMAL;
use indicatif::{ProgressBar, ProgressStyle};
use md5::Digest;
use serde::{Deserialize, Serialize};
use std::fs;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::path::PathBuf;

use crate::error::Error;
use crate::ims::image::http_client::types::PatchImage;

#[derive(Serialize, Deserialize, Debug, Clone)]
struct Artifact {
  pub link: Link,
  pub md5: String,
  #[serde(rename = "type")]
  pub r#type: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct ImageManifest {
  pub created: String,
  #[serde(default = "default_version")]
  pub version: String,
  pub artifacts: Vec<Artifact>,
}

fn default_version() -> String {
  "1.0".to_string()
}

pub async fn exec(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  bos_file: Option<&str>,
  cfs_file: Option<&str>,
  hsm_file: Option<&str>,
  ims_file: Option<&str>,
  image_dir: Option<&str>,
  overwrite_group: bool,
  overwrite_configuration: bool,
  overwrite_image: bool,
  overwrite_template: bool,
) -> Result<(), Error> {
  if !PathBuf::from(&bos_file.unwrap()).exists() {
    return Err(Error::Message(format!(
      "Error, file {} does not exist or cannot be open.",
      &bos_file.unwrap()
    )));
  }
  if !PathBuf::from(&cfs_file.unwrap()).exists() {
    return Err(Error::Message(format!(
      "Error, file {} does not exist or cannot be open.",
      &cfs_file.unwrap()
    )));
  }
  if !PathBuf::from(&ims_file.unwrap()).exists() {
    return Err(Error::Message(format!(
      "Error, file {} does not exist or cannot be open.",
      &ims_file.unwrap()
    )));
  }
  if !PathBuf::from(&hsm_file.unwrap()).exists() {
    return Err(Error::Message(format!(
      "Error, file {} does not exist or cannot be open.",
      &hsm_file.unwrap()
    )));
  }

  // ========================================================================================================
  let current_timestamp = Local::now().format("%Y-%m-%d %H:%M:%S");
  let mut ims_image_manifest = ImageManifest {
    created: current_timestamp.to_string(),
    version: "1.0".to_string(),
    artifacts: vec![],
  };

  let backup_ims_file = ims_file.unwrap().to_string();
  let backup_cfs_file = cfs_file.unwrap().to_string();
  let backup_bos_file = bos_file.unwrap().to_string();
  let backup_hsm_file = hsm_file.unwrap().to_string();

  let ims_image_name: String = get_image_name_from_ims_file(&backup_ims_file);
  println!(" Image name: {}", ims_image_name);

  println!(
    "\tinitrd file: {}",
    image_dir.unwrap().to_string() + "/initrd"
  );
  println!(
    "\tkernel file: {}",
    image_dir.unwrap().to_string() + "/kernel"
  );
  println!(
    "\trootfs file: {}",
    image_dir.unwrap().to_string() + "/rootfs"
  );

  // These should come from the manifest, but let's assume these values are correct
  let vec_backup_image_files = vec![
    image_dir.unwrap().to_string() + "/initrd",
    image_dir.unwrap().to_string() + "/kernel",
    image_dir.unwrap().to_string() + "/rootfs",
  ];

  for file in &vec_backup_image_files {
    if !PathBuf::from(&file).exists() {
      return Err(Error::Message(format!(
        "Error, file {} does not exist or cannot be open.",
        &file
      )));
    }
  }

  println!("Calculating image artifact checksum...");
  calculate_image_checksums(&mut ims_image_manifest, &vec_backup_image_files);

  // println!("{:?}", ims_image_manifest);

  // Do we have another image with this name?
  println!("\n\nRegistering image with IMS...");
  let ims_image_id_rslt = ims_register_image(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &ims_image_name,
    overwrite_image,
  )
  .await;

  let ims_image_id: String = match ims_image_id_rslt {
    Ok(value) => value,
    Err(e) => {
      return Err(Error::Message(format!("{}", e)));
    }
  };

  println!("Ok, IMS image ID: {}", &ims_image_id);

  println!("\nUploading image artifacts to s3...");
  s3_upload_image_artifacts(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &ims_image_id,
    &mut ims_image_manifest,
    &vec_backup_image_files,
  )
  .await;
  println!("\nUpdating IMS image record with the new location in s3...");
  log::debug!("Updating image record with location of the newly generated manifest.json data");
  ims_update_image_add_manifest(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &ims_image_name,
    &ims_image_id,
  )
  .await;
  println!("Ok");

  println!("\nCreating HSM group...");
  create_hsm_group_from_file(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &backup_hsm_file,
    overwrite_group,
  )
  .await;
  println!("Ok");

  println!("\nUploading CFS configuration...");
  // create a new CFS configuration based on the original CFS file backed up previously
  // this operation is simple as the file only has git repos and commits
  create_cfs_config(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &backup_cfs_file,
    overwrite_configuration,
  )
  .await;

  println!("\nUploading BOS sessiontemplate...");
  // Create a new BOS session template based on the original BOS file backed previously
  create_bos_sessiontemplate(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &backup_bos_file,
    &ims_image_id,
    overwrite_template,
  )
  .await;

  println!("\nDone, the image bundle, HSM group, CFS configuration and BOS sessiontemplate have been restored.");

  // ========================================================================================================

  Ok(())
}

async fn create_bos_sessiontemplate(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  bos_file: &String,
  ims_image_id: &String,
  overwrite: bool,
) {
  let file_content = File::open(bos_file)
    .expect(&format!("Unable to read BOS JSON file '{}'", bos_file));

  let bos_json: BosSessionTemplate =
    serde_json::from_reader(BufReader::new(file_content))
      .expect("BOS JSON file does not have correct format.");

  let bos_sessiontemplate_name = bos_json.name.unwrap();

  // BOS sessiontemplates need the new ID of the image!
  log::debug!("BOS sessiontemplate name: {}", &bos_sessiontemplate_name);

  let vector = bos::template::http_client::v2::get(
        shasta_token,
        shasta_base_url,
        shasta_root_cert,
        Some(&bos_sessiontemplate_name),
    )
    .await
    .unwrap_or_else(|error| {
        eprint!(
            "Error: unable to query CSM to get list of BOS sessiontemplates. Error returned: {}",
            error
        );
        std::process::exit(1);
    });

  log::debug!("BOS sessiontemplate filtered: {:#?}", vector);

  if !vector.is_empty() {
    if !overwrite {
      println!("Looks like you do not want to continue, bailing out.");
      std::process::exit(2)
    } else {
      match bos::template::http_client::v2::delete(
                shasta_token,
                shasta_base_url,
                shasta_root_cert,
                &bos_sessiontemplate_name,
            )
            .await
            {
                Ok(_) => log::debug!(
                    "Ok BOS session template {}, deleted.",
                    &bos_sessiontemplate_name
                ),
                Result::Err(err1) => panic!(
                    "Error, unable to delete BOS session template. Cannot continue. Error: {}",
                    err1
                ),
            };
    }
  }

  let file_content = File::open(bos_file)
    .expect(&format!("Unable to read BOS JSON file '{}'", bos_file));

  let mut bos_sessiontemplate: BosSessionTemplate =
    serde_json::from_reader(BufReader::new(file_content))
      .expect("BOS JSON file does not have correct format.");

  let path_modified =
    format!("s3://boot-images/{}/manifest.json", ims_image_id);

  bos_sessiontemplate
    .boot_sets
    .as_mut()
    .unwrap()
    .get_mut("compute")
    .unwrap()
    .path = Some(path_modified);

  log::debug!("BOS sessiontemplate loaded:\n{:#?}", bos_sessiontemplate);
  log::debug!("BOS sessiontemplate modified:\n{:#?}", &bos_sessiontemplate);

  match bos::template::http_client::v2::put(
        shasta_token,
        shasta_base_url,
        shasta_root_cert,
        &bos_sessiontemplate,
        &bos_sessiontemplate_name,
    )
    .await
    {
        Ok(_result) => println!(
            "Ok, BOS session template {} created successfully.",
            &bos_sessiontemplate_name
        ),
        Err(e1) => panic!(
            "Error, unable to create BOS sesiontemplate. Error returned by CSM API: {}",
            e1
        ),
    }
}

/// Creates a CFS config on the current CSM system, based on the CFS file generated by manta migrate backup
/// panics with an error message if creation fails
async fn create_cfs_config(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  cfs_file: &String,
  overwrite: bool,
) {
  let file_content = File::open(cfs_file)
    .expect(&format!("Unable to read CFS JSON file '{}'", cfs_file));

  let cfs_configuration: CfsConfigurationResponse =
    serde_json::from_reader(BufReader::new(file_content))
      .expect("CFS JSON file does not have correct format.");

  // CFS needs to be cleaned up when loading into the system, the filed lastUpdate should not exist
  let cfs_config_name = cfs_configuration.name;

  // Get all CFS configurations, this is ugly
  let cfs_config_vec = cfs::configuration::http_client::v3::get(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    Some(&cfs_config_name),
  )
  .await
  .unwrap_or_else(|error| {
    eprint!(
      "Error: Unable to fetch CFS configuration. Error returned by CSM API: {}",
      error
    );
    std::process::exit(1);
  });

  if !cfs_config_vec.is_empty() {
    if !overwrite {
      println!("Looks like you do not want to continue, bailing out.");
      std::process::exit(2)
    }

    match cfs::configuration::http_client::v3::delete(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      cfs_config_name.as_str(),
    )
    .await
    {
      Ok(_) => {
        log::debug!("Ok CFS configuration {}, deleted.", cfs_config_name)
      }
      Result::Err(error) => panic!(
        "Error, unable to delete configuration. Cannot continue. Error: {}",
        error
      ),
    };
  }

  // At this point we're sure there's either no CFS config with that name
  // or that the user wants to overwrite it, so let's do it

  let file_content = File::open(cfs_file)
    .expect(&format!("Unable to read CFS JSON file '{}'", cfs_file));

  let cfs_configuration: CfsConfigurationRequest =
    serde_json::from_reader(BufReader::new(file_content))
      .expect("CFS JSON file does not have correct format.");

  log::debug!("CFS config:\n{:#?}", &cfs_configuration);

  match cfs::configuration::http_client::v3::put(
        shasta_token,
        shasta_base_url,
        shasta_root_cert,
        &cfs_configuration,
        cfs_config_name.as_str(),
    )
    .await
    {
        Ok(result) => {
            log::debug!("Ok, result: {:#?}", result);
            println!(
                "Ok, CFS configuration {} created successfully.",
                &cfs_config_name
            );
        }
        Err(e1) => panic!(
            "Error, unable to create CFS configuration. Error returned by CSM API: {}",
            e1
        ),
    }
}

/// Add the image manifest field to an IMS image record
/// the manifest field will be: s3://boot-images/{ims_image_id}/manifest.json
async fn ims_update_image_add_manifest(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  ims_image_name: &String,
  ims_image_id: &String,
) {
  match get_fuzzy(shasta_token,
                         shasta_base_url,
                         shasta_root_cert,
                         &[""], // hsm_group_name
                         Some(ims_image_name.clone().as_str()),
                         None).await {
        Ok(_vector) => {
            if _vector.is_empty() {
                panic!("Error: there are no images stored with id {} in IMS. Unable to update the image manifest", &ims_image_id);
            }
        },
        Err(error) =>  panic!("Error: Unable to determine if there are other images in IMS with the name {}. Error code: {}", &ims_image_name, &error),
    };

  let _ims_record = ims::image::http_client::types::Image {
    name: ims_image_name.clone().to_string(),
    id: Some(ims_image_id.clone().to_string()),
    created: None,
    arch: None,
    link: Some(ims::image::http_client::types::Link {
      etag: None,
      path: format!(
        "s3://boot-images/{}/manifest.json",
        &ims_image_id.to_string()
      ),
      r#type: "s3".to_string(),
    }),
    metadata: None,
  };

  let ims_link = Link {
    etag: None,
    path: format!(
      "s3://boot-images/{}/manifest.json",
      &ims_image_id.to_string()
    ),
    r#type: "s3".to_string(),
  };
  let rec = PatchImage {
    link: Some(ims_link),
    arch: None,
    metadata: None,
  };

  match patch(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &ims_image_id.to_string(),
    &rec,
  )
  .await
  {
    Ok(()) => log::debug!("Image updated"),
    Err(e) => panic!(
      "Error, unable to modify the record of the image. Err msg: {}",
      e
    ),
  };
}

/// Uploads to s3 under boot-images/ims_image_id all the files that
/// vec_image_files refers to. If upload successful, it modifies
/// ImageManifest to point to the right place within s3
async fn s3_upload_image_artifacts(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  ims_image_id: &String,
  ims_image_manifest: &mut ImageManifest,
  vec_image_files: &Vec<String>,
) {
  let bucket_name = "boot-images";
  let object_path = ims_image_id;

  // Connect and auth to S3
  let sts_value = match ims::s3_client::s3_auth(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
  )
  .await
  {
    Ok(sts_value) => {
      log::debug!("STS token:\n{:#?}", sts_value);
      sts_value
    }
    Err(error) => panic!(
      "Unable to authenticate with s3 when uploading images. Error: {}",
      error
    ),
  };

  for file in vec_image_files {
    let filename = Path::new(file).file_name().unwrap();
    let file_size = match fs::metadata(file) {
      Ok(_file_metadata) => {
        let res: String = humansize::format_size(_file_metadata.len(), DECIMAL);
        res
      }
      Err(e) => {
        eprintln!(
          "Unable to fetch file metadata info, faking the value. Error: {}",
          e
        );
        "-1".to_string()
      }
    };

    let full_object_path =
      format!("{}/{}", &object_path, &filename.to_string_lossy());
    println!(
      "File {:?} ({}) to s3://{}/{}.",
      &file, &file_size, &bucket_name, &full_object_path
    );
    let etag: String;
    if fs::metadata(file).unwrap().len() > 1024 * 1024 * 5 {
      etag = match ims::s3_client::s3_multipart_upload_object(
        &sts_value,
        &full_object_path,
        bucket_name,
        file,
      )
      .await
      {
        Ok(result) => {
          log::debug!("Artifact uploaded successfully.");
          result
        }
        Err(error) => panic!("Unable to upload file to s3. Error {}", error),
      };
    } else {
      etag = match ims::s3_client::s3_upload_object(
        &sts_value,
        &full_object_path,
        bucket_name,
        file,
      )
      .await
      {
        Ok(result) => {
          println!("Ok");
          result
        }
        Err(error) => panic!("Unable to upload file to s3. Error {}", error),
      };
    }

    // I'm pretty sure there's a better way to do this...
    if file.contains("kernel") {
      for artifact in ims_image_manifest.artifacts.iter_mut() {
        if !etag.is_empty() {
          // assign eTag if returned by s3, otherwise set to none
          artifact.link.etag = Some(etag.clone());
        }
        if artifact.r#type.contains("kernel") {
          artifact.link.path = "s3://".to_string()
            + bucket_name
            + "/"
            + &object_path.to_string()
            + "/kernel";
          break;
        }
      }
    } else if file.contains("rootfs") {
      for artifact in ims_image_manifest.artifacts.iter_mut() {
        if !etag.is_empty() {
          // assign eTag if returned by s3, otherwise set to none
          artifact.link.etag = Some(etag.clone());
        }
        if artifact.r#type.contains("rootfs") {
          artifact.link.path = "s3://".to_string()
            + bucket_name
            + "/"
            + &object_path.to_string()
            + "/rootfs";
          break;
        }
      }
    } else if file.contains("initrd") {
      for artifact in ims_image_manifest.artifacts.iter_mut() {
        if !etag.is_empty() {
          // assign eTag if returned by s3, otherwise set to none
          artifact.link.etag = Some(etag.clone());
        }
        if artifact.r#type.contains("initrd") {
          artifact.link.path = "s3://".to_string()
            + bucket_name
            + "/"
            + &object_path.to_string()
            + "/initrd";
          break;
        }
      }
    }
  }

  log::debug!("Writing the new manifest.json file with the correct new ID");
  let new_manifest_file_name = String::from("new-manifest.json");
  let new_manifest_file_path = Path::new(vec_image_files.first().unwrap())
    .parent()
    .unwrap()
    .join(&new_manifest_file_name);
  let new_manifest_file = File::create(&new_manifest_file_path)
    .expect("new manifest.json file could not be created.");
  serde_json::to_writer_pretty(&new_manifest_file, &ims_image_manifest)
    .expect("Unable to write new manifest.json file");

  log::debug!("Uploading the new manifest.json file");
  let manifest_full_object_path = format!("{}/manifest.json", &object_path);
  println!(
    "File {:?} -> s3://{}/{}.",
    &new_manifest_file_name, &bucket_name, &manifest_full_object_path
  );

  match ims::s3_client::s3_upload_object(
    &sts_value,
    &manifest_full_object_path,
    bucket_name,
    &new_manifest_file_path.to_owned().to_string_lossy(),
  )
  .await
  {
    Ok(_result) => {
      println!("OK");
    }
    Err(error) => panic!("Unable to upload file to s3. Error {}", error),
  };
}

/// Return the md5sum of a file
fn file_md5sum(filename: PathBuf) -> Digest {
  log::debug!("File {:?}...", &filename);

  let f = File::open(filename).unwrap();
  // Find the length of the file
  let len = f.metadata().unwrap().len();
  // Decide on a reasonable buffer size (100MB in this case, fastest will depend on hardware)
  let buf_len = len.min(100_000_000) as usize;
  let mut buf = BufReader::with_capacity(buf_len, f);
  let mut context = md5::Context::new();
  let bar = ProgressBar::new(len);
  bar.set_style(ProgressStyle::with_template(BAR_FORMAT).unwrap());

  loop {
    // Get a chunk of the file
    let part = buf.fill_buf().unwrap();
    // If that chunk was empty, the reader has reached EOF
    if part.is_empty() {
      break;
    }
    // Add chunk to the md5
    context.consume(part);
    // Tell the buffer that the chunk is consumed
    let part_len = part.len();
    buf.consume(part_len);
    bar.inc(part_len as u64);
  }
  let digest = context.compute();
  bar.finish();

  digest
}
/// Calculates the md5sum of all the files in the `vec_backup_image_files` vector and updates
///  the image manifest at `ims_image_manifest`
fn calculate_image_checksums(
  image_manifest: &mut ImageManifest,
  vec_backup_image_files: &Vec<String>,
) {
  for file in vec_backup_image_files {
    let file_size = match fs::metadata(file) {
      Ok(_file_metadata) => {
        let res: String = humansize::format_size(_file_metadata.len(), DECIMAL);
        res
      }
      Err(e) => {
        eprintln!(
          "Unable to fetch file metadata info, faking the value. Error: {}",
          e
        );
        "-1".to_string()
      }
    };
    println!("File {:?} ({})...", &file, &file_size);
    let artifact;
    let mut fp = PathBuf::new();
    fp.push(file);
    let digest = file_md5sum(fp);

    if file.contains("kernel") {
      artifact = Artifact {
        md5: format!("{:x}", digest),
        link: Link {
          path: "path".to_string(),
          r#type: "s3".to_string(),
          etag: None,
        },
        r#type: "application/vnd.cray.image.kernel".to_string(),
      };
    } else if file.contains("rootfs") {
      artifact = Artifact {
        md5: format!("{:x}", digest),
        link: Link {
          path: "path".to_string(),
          r#type: "s3".to_string(),
          etag: None,
        },
        r#type: "application/vnd.cray.image.rootfs.squashfs".to_string(),
      };
    } else {
      artifact = Artifact {
        md5: format!("{:x}", digest),
        link: Link {
          path: "path".to_string(),
          r#type: "s3".to_string(),
          etag: None,
        },
        r#type: "application/vnd.cray.image.initrd".to_string(),
      };
    }
    image_manifest.artifacts.push(artifact);
  }
}

/// Registers in IMS a new image and returns the new id to pass to s3
async fn ims_register_image(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  ims_image_name: &String,
  overwrite: bool,
) -> anyhow::Result<String> {
  let ims_record = Image {
    name: ims_image_name.clone().to_string(),
    id: None,
    created: None,
    link: None,
    arch: None,
    metadata: None,
  };

  let list_images_with_same_name = get_by_name(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &[""], // hsm_group_name
    Some(ims_image_name.clone().as_str()),
    None,
  )
  .await?;

  if !list_images_with_same_name.is_empty() {
    if !overwrite {
      println!("Looks like you do not want to continue, bailing out.");
      std::process::exit(2)
    }
  }

  let json_response = ims::image::http_client::post(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &ims_record,
  )
  .await?;

  Ok(json_response["id"].to_string().replace('"', ""))
}

/// Gets the image name off an IMS yaml file
pub fn get_image_name_from_ims_file(ims_file: &String) -> String {
  // load into memory
  let ims_data = fs::read_to_string(PathBuf::from(&ims_file))
    .expect("Unable to read IMS file file");

  let ims_json: serde_json::Value = serde_json::from_str(&ims_data)
    .expect("HSM JSON file does not have correct format.");

  ims_json[0]["name"].clone().to_string().replace('"', "")
}

// Anything in this function is critical, so the asserts will kill further processing
pub async fn create_hsm_group_from_file(
  // backend: &StaticBackendDispatcher,
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  hsm_file: &String,
  overwrite: bool,
) {
  // Parse HSM group file
  // The file looks like this: [{"gele":["x1001c7s1b1n1","x1001c7s1b0n0","x1001c7s1b1n0","x1001c7s1b0n1"]}]
  // load into memory
  let hsm_data = fs::read_to_string(PathBuf::from(hsm_file))
    .expect("Unable to read HSM JSON file");

  let group_vec: Vec<Group> = serde_json::from_str(&hsm_data)
    .expect("HSM JSON file does not have correct format.");

  for group in group_vec {
    // Create the HSM group
    let group_members_opt =
      group.members.clone().and_then(|members| members.ids);
    match create_new_group(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      &group.label,
      &group_members_opt.unwrap_or_default(),
      &group.exclusive_group.clone().unwrap(),
      &group.description.clone().unwrap(),
      &group.tags.clone().unwrap(),
    )
    .await
    {
      Ok(group) => {
        println!(
          "The HSM group {} has been created successfully.",
          &group.label
        );
      }
      Err(error) => {
        if error.to_string().to_lowercase().contains("409") {
          if overwrite {
            println!("Looks like you want to continue");
            // match backend.delete_group(shasta_token, &group.label).await {
            match delete_group(
              shasta_token,
              shasta_base_url,
              shasta_root_cert,
              &group.label,
            )
            .await
            {
              Ok(_) => {
                // try creating the group again
                // match backend.add_group(shasta_token, group.clone()).await {
                match crate::hsm::group::http_client::post(
                  shasta_token,
                  shasta_base_url,
                  shasta_root_cert,
                  group.clone(),
                )
                .await
                {
                  Ok(_json) => {
                    println!(
                      "The HSM group {} has been created successfully.",
                      &group.label
                    );
                  }
                  Err(e) => {
                    log::error!("Error message {}", e);
                    panic!("Second error creating a new HSM group. Bailing out. Error returned: '{}'", e)
                  }
                }
              }
              Err(e) => {
                log::error!("Error message {}", e);
                panic!(
                  "Error deleting the HSM group {}. Error returned: '{}'",
                  &group.label, e
                )
              }
            }
          } else {
            println!("Not deleting the group, cannot continue the operation.");
            std::process::exit(2);
          }
        } else if error.to_string().to_lowercase().contains("400") {
          eprintln!("Unable to create the group, the API returned code 400. This usually means the HSM file is malformed, or has incorrect xnames for this site in it.");
          std::process::exit(2);
        }
      }
    };
  }
}