{ lib, pkgs, cfg }:

# Transcode voicemail greeting audio files to multiple formats so Asterisk can
# play them without transcoding regardless of the channel's active codec.
# Playback() is called with the path minus extension; Asterisk finds the best.
#
# Returns:
#   { shared   : path | null     — greeting dir for the shared mailbox
#   , persons  : { key : path | null }  — greeting dir per person key
#   }

let
  mkGreetingDir = name: src:
    pkgs.runCommand "greeting-${name}" {
      nativeBuildInputs = [ pkgs.ffmpeg ];
    } ''
      mkdir -p $out
      ffmpeg -i ${src} -ar 8000  -ac 1 -f mulaw           $out/greeting.ulaw
      ffmpeg -i ${src} -ar 8000  -ac 1 -f alaw            $out/greeting.alaw
      ffmpeg -i ${src} -ar 16000 -ac 1 -acodec adpcm_g722 $out/greeting.g722
    '';

in {
  shared =
    if cfg.sharedMailbox != null && cfg.sharedMailbox.greeting != null
      then mkGreetingDir "shared" cfg.sharedMailbox.greeting
      else null;

  persons = lib.mapAttrs (key: person:
    if person.mailbox && person.mailboxGreeting != null
      then mkGreetingDir key person.mailboxGreeting
      else null
  ) cfg.persons;
}
