#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Test the relocation of an export.
usage: test_relocate.py filename.export

To set the environment :
. $ASTER_ROOT/etc/codeaster/profile.sh
export PYTHONPATH=$PYTHONPATH:$ASTER_ROOT/share/codeaster/asrun/unittest

"""

import sys
import os.path as osp

from asrun.run import AsRunFactory
from asrun.core import magic
from asrun.profil import AsterProfil
from asrun.core.server import build_server_from_profile, TYPES
from asrun.common.sysutils import local_full_host
from asrun.common.utils import unique_basename

#unique_basename = None


def main(fname, verbose=False):
    """Run"""
    # initialize objects
    magic.init_logger(debug=False)
    run = AsRunFactory()
    prof = AsterProfil(fname)
    studyid = '01234'

    # very similar to asrun.plugins.default.copy_datafiles_on_server
    sexec = build_server_from_profile(prof, TYPES.EXEC)
    scopy = build_server_from_profile(prof, TYPES.COPY_TO, jobid=studyid)
    forig = prof.get_filename()

    run_on_localhost = sexec.is_localhost()
    if verbose:
        print('run on localhost ?', run_on_localhost)
    remote_prof = prof.copy()
    if not run_on_localhost:
        remote_prof.relocate(local_full_host, scopy.get_proxy_dir(),
                             convert=unique_basename)
    remote_prof.relocate(sexec.host, convert=unique_basename)
    #remote_prof['studyid'] = studyid
    #remote_prof.set_filename(fprof)
    #remote_prof.WriteExportTo(fprof)
    if verbose:
        print(remote_prof)
        print(remote_prof.get_on_serv(local_full_host).get_data().topath())

    local_resu = prof.get_result().get_on_serv(local_full_host)
    local_nom, local_other = local_resu.get_type('nom', with_completion=True)
    if verbose:
        for dst in local_other.topath():
            bname = unique_basename(dst)
            src = osp.join("/proxy_dir", bname)
            fsrc = "user" + "@" +  "host" + ":" + src
            print("copy %s to %s" % (fsrc, dst))
        for dst in local_nom.topath():
            bname = osp.basename(dst)
            src = osp.join("/proxy_dir", bname)
            fsrc = "user" + "@" +  "host" + ":" + src
            print("copy %s to %s" % (fsrc, dst))
        #scopy.copyfrom(convert=unique_basename, *[e.path for e in local_resu])
    return 0, remote_prof


if __name__ == '__main__':
    iret, prof = main(*sys.argv[1:])
