(**************************************************************************)
(*  Copyright © 2009 Stéphane Glondu <steph@glondu.net>                   *)
(*  Copyright © 2013 Johannes Schauer <j.schauer@email.de>                *)
(*                                                                        *)
(*  This program is free software: you can redistribute it and/or modify  *)
(*  it under the terms of the GNU Affero General Public License as        *)
(*  published by the Free Software Foundation, either version 3 of the    *)
(*  License, or (at your option) any later version, with the additional   *)
(*  exemption that compiling, linking, and/or using OpenSSL is allowed.   *)
(*                                                                        *)
(*  This program is distributed in the hope that it will be useful, but   *)
(*  WITHOUT ANY WARRANTY; without even the implied warranty of            *)
(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *)
(*  Affero General Public License for more details.                       *)
(*                                                                        *)
(*  You should have received a copy of the GNU Affero General Public      *)
(*  License along with this program.  If not, see                         *)
(*  <http://www.gnu.org/licenses/>.                                       *)
(**************************************************************************)

open Printf
open Ben.Core
open Ben.Error
open Data
open Ben.Modules
module Marshal = Ben.Marshal.Make (Marshallable)
open Marshallable

let p = Clflags.progress
let ( / ) = Filename.concat

let download_sources () =
  if !Clflags.areas = [] then raise Nothing_to_download;
  let wquiet = if !Clflags.verbose then "" else "--silent" in
  let dst = !Clflags.cache_dir / "Sources" in
  let tmp = Filename.temp_file "Sources." "" in
  let commands =
    Ben.Parallel.map
      (fun area ->
        let url =
          sprintf "%s/dists/%s/%s/source/Sources%s" !Clflags.mirror_sources
            !Clflags.suite area
            (Ben.Compression.extension !Clflags.preferred_compression_format)
        in
        if !Clflags.dry_run then p "Would download %s\n" url;
        let cmd =
          sprintf "{ curl -L %s %s | %s >> %s; }" wquiet (escape_for_shell url)
            (Ben.Compression.display_tool !Clflags.preferred_compression_format)
            tmp
        in
        cmd)
      !Clflags.areas
  in
  let cmd = sprintf "%s && mv %s %s" (String.concat " && " commands) tmp dst in
  if not !Clflags.dry_run then (
    p "Downloading %s...\n" dst;
    let r = Sys.command cmd in
    if r <> 0 then raise (Curl_error r)
    else FileUtil.rm ~force:FileUtil.Force [ tmp ])

let download_binaries arch =
  if !Clflags.areas = [] then raise Nothing_to_download;
  let wquiet = if !Clflags.verbose then "" else "--silent" in
  let dst = (!Clflags.cache_dir / "Packages_") ^ arch in
  let tmp = Filename.temp_file "Packages." "" in
  let commands =
    Ben.Parallel.map
      (fun area ->
        let url =
          sprintf "%s/dists/%s/%s/binary-%s/Packages%s" !Clflags.mirror_binaries
            !Clflags.suite area arch
            (Ben.Compression.extension !Clflags.preferred_compression_format)
        in
        if !Clflags.dry_run then p "Would download %s\n" url;
        let cmd =
          sprintf "{ curl -L %s %s | %s >> %s; }" wquiet (escape_for_shell url)
            (Ben.Compression.display_tool !Clflags.preferred_compression_format)
            tmp
        in
        cmd)
      !Clflags.areas
  in
  let cmd = sprintf "%s && mv %s %s" (String.concat " && " commands) tmp dst in
  if not !Clflags.dry_run then (
    p "Downloading %s...\n" dst;
    let r = Sys.command cmd in
    if r <> 0 then raise (Curl_error r)
    else FileUtil.rm ~force:FileUtil.Force [ tmp ])

let download_all architectures =
  download_sources ();
  Ben.Parallel.iter download_binaries architectures

let save_cache () =
  let architectures = !Clflags.debian_architectures in
  if !Clflags.use_cache then
    let file = Clflags.get_cache_file () in
    let () = p "Generating %s...\n" file in
    let src_map = Data.file_origin.get_sources M.empty in
    let bin_map =
      Ben.Parallel.fold Data.file_origin.get_binaries PAMap.empty architectures
        PAMap.fusion
    in
    let bin_map = Data.inject_build_status architectures src_map bin_map in
    let data = { src_map; bin_map } in
    Marshal.dump file data

let main () =
  download_all !Clflags.debian_architectures;
  save_cache ()

let frontend =
  {
    Frontend.name = "download";
    Frontend.main;
    Frontend.anon_fun = (fun _ -> ());
    Frontend.help = [];
  }
