package nxm.sys.intr;

import nxm.sys.lib.FileName;
import nxm.sys.lib.Intrinsic;

/**
  Handles setting and restoring the HOME path for user macros.

  @author Jeff Schoen
*/
public class Homepath extends Intrinsic {

  /** default constructor */
  public Homepath () {}

  public int process () {

    // Get parameters
    String path = MA.getS("PATH");
    String opt  = MA.getS("OPT");

    // since 3.1.0/3.1.1, the 4 lines below added to support HOMEPATH 'sticking' to CWD (Bug 2481)
    boolean trackCWD = MA.getState("/CWD", false);
    if (trackCWD) {
      MR.put("AUX._TRACKCWD_", trackCWD, nxm.sys.lib.Table.FORCE, this);  // special entry in AUX table
      MR.put("AUX.HOMEPATH", MR.getS("AUX.CWD"));
    } else {
      MR.remove("AUX._TRACKCWD_");
    }

    if (path.equals("RESTORE") || MA.getState("/RESTORE")) {
      String oldpath = MR.getS("OLDHOMEPATH");
      if (oldpath!=null) {
        MR.put("AUX.HOMEPATH", oldpath);
        path = oldpath; // save to path so that we can validate that it exists below
      }
      else M.warning("Result OLDHOMEPATH not found");
      MR.remove("OLDHOMEPATH");
    }
    else if (path.length() > 0) {
      if (MA.getState("/STORE", true)) {
        String oldpath = MR.getS("AUX.HOMEPATH");
        MR.put("OLDHOMEPATH",oldpath);
      }
      if (opt.length() > 0) {
        path = M.io.name(path,"","",opt);
      } else if (path.equals("TEST")) {
        path = M.io.name("test","","","SYS");
      } else {
        FileName fn = MA.getFileName ("PATH");
        path = fn.getFullName();
        path = FileName.terminatePath (path);
      }
      MR.put("AUX.HOMEPATH", path);
    }
    else {
      path = MR.getS("AUX.HOMEPATH");
      verbose = true; // to force printing current HomePath
    }

    if (verbose) {
      M.println("HomePath = "+path);  // since 3.7.1 using M.println instead of M.terminal.writeln to allow logging - NXM-1813
    }

    if (!MA.getState("/NOWARN",false) && !M.io.exists(path)) {
      M.warning("Specified HomePath does not exist: "+path);
    }
    return FINISH;
  }

}
