# vim: set filetype=sh :
#   copyright: Bernd Schumacher <bernd.schumacher@hpe.com> (2007-2020)
#     license: GNU General Public License, version 3
# mylib - customized usage of shellia
# can be called as
#   #/bin/sh
#   LOG_DIR=/<path_to_dir>/
#   . /usr/share/doc/shellia/examples/mylib

# we want an easy to remember function to be uses in case of an error
# we also use exit code 1
# each error Message should start equal
err()
{
  ia_exiterr 1 "ERROR: $*"
}

# we want an easy to remember function to give information to the user on stderr
# this info should always be logged
# this information should not be given to stderr if our script has to be silent
info()
{
  [ "$ia_use_silent" ] && ia_log "$@" || ia_logerr "$@"
}

log()
{
  ia_log "$@"
}

# this command is for shellia scripts on remote server
# we use ia_nocheck, to not recheck output of remote shellia script again
# macro_file <hostname> <eval-executeable-command>
#
# we create a tempfile to save loginfo while running on remote host
# we add the remote tempfile to our local logfile
# we want the same interactive-mode on remote server as on local server
#
#            | automatically find out | manually define if 
#            | if cmd uses shellia    | cmd uses shellia
# -----------+------------------------+-----------------------------------------
# remote     | eval "$ia_init"     (A)| eval "$ia_init"                      (B)
# command is | ...                    | ...
# controlled | ia_nocheck             | ia_nocheck
# by shellia | my_ssh <host> "<cmd>"  | ia_add "my_ssh --ia <host> \"<cmd>\""
#            |  ...                   | ...
#            | ia -c                  | ia -c
# -----------+------------------------+-----------------------------------------
# remote     | eval "$ia_init"     (C)| eval "$ia_init"                      (D)
# command is | ...                    | ...
# not        | my_ssh <host> "<cmd>"  | ia_add "my_ssh --no-ia <host> \"<cmd>\""
# controlled | ...                    | ...
# by shellia | ia -c                  | ia -c
#
my_ssh()
{
  #global ssh
  #global ssh_opts
  local ia # set this if command executed on target server uses shellia
  local ssh_host
  local ret
  local tf
  local cmd
  #ia_dev_dbg "my_ssh: #=<$#> 1=<$1> 2=<$2> 3=<$3> 4=<$4> 5=<$5> 6=<$6> 7=<$7>"

  ia=""
  ssh_more_opts=""
  while :; do
    if [ "$1" = "--ia" -o "$1" = "--no-ia" ]; then
      ia="$1"
      shift
    elif [ "$1" = "-x" ]; then
      ssh_more_opts="$2"
      shift 2
    else
      break
    fi
  done

  ssh_host="$1"
  shift

  if [ ! "$ia" ]; then
    # we are actually adding commands with ia_add
    if [ "$(ia_is_nocheck)" ]; then # (A)
      # ia_nocheck was called before this cmd. => cmd is controlled by shellia
      ia="--ia"
    elif [ "$(echo "$*" | grep "<-i>")" ]; then # (A)
      # cmd contains shellia option, => cmd is controlled by shellia, but forgot to call ia_nocheck
      ia_nocheck
      ia="--ia"
    else # (B)
      # cmd is not controlled by shellia
      ia="--no-ia"
    fi
    cmd="$(/bin/echo "$*" | ia_easy_backslash -2)"
    ia_add "my_ssh $ia $ssh_more_opts $ssh_host \"$cmd\""
    return $?
  fi

  [ "$ssh" ] || ssh="ssh"
  [ "$ssh_opts" ] || ssh_opts="-q -o \"ConnectionAttempts 1\" -o \
    \"FallBackToRsh no\" -o \"GlobalKnownHostsFile /dev/null\" -o \
    \"KeepAlive yes\" -o \"StrictHostKeyChecking no\" -o \
    \"UserKnownHostsFile /dev/null\" -o \"NoHostAuthenticationForLocalhost yes\" -o \
    \"NumberOfPasswordPrompts 1\""

  cmd="$(/bin/echo "$*" | ia_easy_backslash)"

  if [ "$ia" = "--ia"  ]; then # (C)
    tf="$(eval "ssh -n $ssh_opts \"$ssh_host\" mktemp")" # option -n is needed to allow to pipe | my_ssh
    log "|ssh-$ssh_host: temp logfile $tf"
    ( eval "$ssh $ssh_opts \"$ssh_host\" \"export ia_red=\\\"$ia_red\\\"; \
      export ia_green=\\\"$ia_green\\\"; export ia_orange=\\\"$ia_orange\\\"; \
      export ia_no_color=\\\"$ia_no_color\\\"; export ia_use_silent=\\\"$ia_use_silent\\\"; \
      export ia_logfile=\\\"$tf\\\"; export ia_prefix_head=\\\"$ia_head/ssh-$ssh_host\\\"; \
      export dbg_run_level=\\\"$dbg_run_level\\\"; export dbg_run_names=\\\"$dbg_run_names\\\"; \
      $cmd\"" 2>&$ia_direct_stderr_fd )
    ret=$?
    eval "ssh $ssh_opts \"$ssh_host\" \"cat $tf; rm -f $tf\"" >> $ia_logfile
  else # (D)
    log "|ssh-$ssh_host:"
    ( eval "$ssh $ssh_more_opts $ssh_opts \"$ssh_host\" \"export ia_use_silent=1; $cmd\"" )
    ret=$?
  fi

  if [ $ret -eq 255 ]; then
    info "ssh to \"$ssh_host\" does not work (ssh \"$ssh_host\" $*)"
  fi

  return $ret
}

# if we call another local-script that uses shellia, we will do this with
# do_file <-i> <local-script> <-i> -- <local-script-args>
my_file()
{
  local ia

  ia=""
  while :; do
    if [ "$1" = "--ia" -o "$1" = "--no-ia" ]; then
      ia="$1"
      shift
    else
      break
    fi
  done

  if [ ! "$ia" ]; then
    # we are actually adding commands with ia_add
    if [ "$ia_is_nocheck" ]; then
      # ia_nocheck was called before this cmd. => cmd is controlled by shellia
      ia="--ia"
    elif [ "$(echo "$*" | grep "<-i>")" ]; then
      # cmd contains shellia option, => cmd is controlled by shellia, but forgot to call ia_nocheck
      ia_nocheck
      ia="--ia"
    else
      # cmd is not controlled by shellia
      ia="--no-ia"
    fi

    cmd="$(/bin/echo "$1" | ia_easy_backslash)"
    ia_add "my_file $ia \"$cmd\""
    return $?
  fi

  # we are actually executing cmd with ia command
  log "|start-file $*"
  if [ "$ia" = "--ia"  ]; then
    # the other shellia file called by this script should use the same logfile and silent value
    ( export ia_logfile; export ia_use_silent; export ia_red; export ia_green; \
      export ia_orange; export ia_no_color; \
      export ia_prefix_head="$ia_head/new-file"; eval "$1" 2>&$ia_direct_stderr_fd )
  else
    # called file is not shellia controlled
    eval "$1"
  fi
}

# if we call a remote-script that uses shellia per ssh, we will do this with run_ssh
# e.g. if we want to call the shellia example hello_world we would use the line:
# ia_add "run_ssh <-i> /usr/share/doc/shellia/examples/hello_world <-i>"

# we want to log to directory /var/log/mylib/ (if LOG_DIR is not otherwise set)
# we want to have a logfile with the name of our script
# we want 3 rotating copies
if ! [ "$ia_logfile" ]; then
  ia_logfile="${LOG_DIR:-/var/log/mylib}/$(basename $0)"
  [ -f $ia_logfile.2 ] && mv $ia_logfile.2 $ia_logfile.3
  [ -f $ia_logfile.1 ] && mv $ia_logfile.1 $ia_logfile.2
  [ -f $ia_logfile ] && mv $ia_logfile $ia_logfile.1
fi

# we want our script only to import this file (which automatically includes shellia libs)
# we prefer a local copy of ia, if it exists
[ -f ia ] && . ./ia || . /usr/share/shellia/ia
