#!/usr/bin/env python3

#import re
import subprocess
import os
from pathlib import Path

#fetch list of pops from ebas
cmd = f'ebas_list_comp -g pop -m precip,precip+dry_dep,wetdep,precip_tot'

print("Running:", cmd)

res = subprocess.run(cmd, shell=True, capture_output=True, check=True)
lines = res.stdout.splitlines()[2:]

comp = []
popcomps = []
for l in lines:
    comp = l.split()
    
    if comp and comp[0] not in popcomps:
        popcomps.append(comp[0].decode("utf-8"))

#extract and rename files for each component
folder = Path("/home/annehj/helene/")
for c in popcomps:
    cmd = f'ebas_extract --format NetCDF --createfiles --long_timeseries -c {c} --amount -m precip -s NO0001 --createfiles' 
    print("Running:", cmd)

    subprocess.run(cmd, shell=True, check=True)
    for file in folder.glob("*..*.nc"):
        print(file)
        new_name = file.name.replace("..", "." + c + ".")
#        new_name = file.name.replace("..", "." + c + ".", 1)
        print("newname", new_name)
        os.rename(file, new_name)
