#! /usr/bin/env python

# ===================================================================

import sys
import os

# ===================================================================

from crds.core import timestamp, log, utils
from crds.core.pysh import *
from crds import list

# ===================================================================

usage("<instruments...>", 1, help="""

crds_dataset_capture interacts with the CRDS server to dump dataset
matching parameters for the instruments specified on the command 
line.  It's a convenience wrapper that automates more primitive
features in 'crds list'.
""")

def capture(instrument):
    ids_file = instrument + ".ids.txt"
    headers_file = instrument + ".headers.json"

    old_out = sys.stdout

    log.info("Capturing", repr(ids_file))
    with open(ids_file, "w+") as sys.stdout:
        errors = list.ListScript(f"crd.list --dataset-ids {instrument} --stats --log-time")()

    log.info("Capturing", repr(ids_file), "to", repr(headers_file))
    with open(headers_file, "w+") as sys.stdout:
        errors += list.ListScript(f"crds.list --dataset-headers @{ids_file} --json --stats --log-time")()

    sys.stdout = old_out
    return errors

def main(instruments):
    now = timestamp.now("T").replace(":","-").split(".")[0]
    capture_dir = "capture-" + now

    log.set_log_time(True)

    log.info("="*80)
    log.info("Capturing", repr(instruments), "to", repr(capture_dir))
    sh("mkdir ${capture_dir}")
    os.chdir(capture_dir)

    errors = 0
    for instrument in instruments:
        errors += capture(instrument)
    return errors

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

