#!/bin/bash

tkis_prepare(){

  if [[ $tkis_command != "wipe" && $tkis_command != "complete-clean" ]] ; then
    if [[ $tkis_process == "" ]] ; then
      error "No build specified, and a build is required to run the $color_reset$color_notice$tkis_command$color_reset$color_error command"
    fi
  fi

  if [[ $tkis_command == "wipe" ]] ; then
    echo -e "${color_notice}Performing Wipe${color_reset}"
    echo
    tkis_security_check_remove $WO
    rm -Rf ${WO}*
    rm -Rf ${tkis_data}*
    rm -Rf ${tkis_output}*
    exit 0
  fi

  if [[ $tkis_command == "complete-clean" ]] ; then
    echo -e "${color_notice}Performing Complete Clean${color_reset}"
    echo
    tkis_security_check_remove $WO
    tkis_security_check_remove $TO
    rm -Rf ${WO}*
    rm -Rf ${TO}*
    rm -Rf ${tkis_data}*
    rm -Rf ${tkis_output}*
    exit 0
  fi

  if [[ $tkis_command == "clean" ]] ; then
    echo -e "${color_notice}Performing Clean${color_reset}"
    echo
    if [[ $tkis_process != "" ]] ; then
      rm -vf ${tkis_output}error{,.$tkis_process} ${tkis_data}resume.${tkis_process}.rule{,.*} ${tkis_output}debug{,.$tkis_process} ${tkis_output}build_time{,.$tkis_process} ${tkis_data}environment.$tkis_process ${tkis_data}patched-*.${tkis_process} ${tkis_data}$tkis_process.last_directory.*
    else
      rm -vf ${tkis_output}error ${tkis_data}resume.rule{,.*} ${tkis_output}debug ${tkis_output}build_time ${tkis_data}environment ${tkis_data}patched-* ${tkis_data}last_directory.*
    fi
    exit 0
  elif [[ $tkis_command == "clean-upgrade" || $tkis_command == "clean-execute" ]] ; then
    echo -e "${color_notice}Performing Clean${color_reset}"
    echo
    if [[ $tkis_process != "" ]] ; then
      rm -vf ${tkis_output}error{,.$tkis_process} ${tkis_data}resume.${tkis_process}.rule{,.$tkis_program_name} ${tkis_output}debug{,.$tkis_process} ${tkis_output}build_time{,.$tkis_process} ${tkis_data}environment.$tkis_process ${tkis_data}patched-$tkis_program_name.${tkis_process} ${tkis_data}$tkis_process.last_directory.$tkis_program_name
    else
      rm -vf ${tkis_output}error ${tkis_data}resume.rule{,.$tkis_program_name} ${tkis_output}debug ${tkis_output}build_time ${tkis_data}environment ${tkis_data}patched-$tkis_program_name ${tkis_data}last_directory.$tkis_program_name
    fi
    exit 0
  fi

  if [[ $tkis_command == "rerun" || $tkis_command == "rerun-upgrade" || $tkis_command == "rerun-execute" ]] ; then
    echo -e "${color_notice}Performing Re-Run, Starting From the Top of the Last Run Rule${color_reset}"
    rm -vf ${tkis_output}error{,.$tkis_process} ${tkis_data}resume.${tkis_process}.rule{,.*} ${tkis_output}debug{,.$tkis_process} ${tkis_output}build_time{,.$tkis_process} ${tkis_data}$tkis_process.last_directory.*

    if [[ $tkis_command == "rerun" ]] ; then
      tkis_command="system"
    elif [[ $tkis_command == "rerun-upgrade" ]] ; then
      tkis_command="upgrade"
    else
      tkis_command="execute"
    fi
  fi

  if [[ $tkis_command == "resume" || $tkis_command == "resume-upgrade" || $tkis_command == "resume-execute" ]] ; then
    echo -e "${color_notice}Performing Resume, Picking Up From Previous Halt Position of the Last Run Rule${color_reset}"
    rm -vf ${tkis_output}error{,.$tkis_process} ${tkis_output}debug{,.$tkis_process} ${tkis_output}build_time{,.$tkis_process}

    if [[ $tkis_command == "resume" ]] ; then
      tkis_command="system"
    elif [[ $tkis_command == "resume-upgrade" ]] ; then
      tkis_command="upgrade"
    else
      tkis_command="execute"
    fi
  fi

  if [[ $tkis_force_install == "yes" ]] ; then
    rm -vf ${tkis_data}installed.$tkis_process
  fi

  if [[ -f ${tkis_output}error ]] ; then
    error "CRITICAL: $color_reset$color_notice${tkis_output}error$color_reset$color_error does and must not exist, deal with the issue and delete the file to continue"
  fi

  if [[ -f ${tkis_output}error.$tkis_process ]] ; then
    error "CRITICAL: $color_reset$color_notice${tkis_output}error.$tkis_process$color_reset$color_error does and must not exist, deal with the issue and delete the file to continue"
  fi
}

tkis_install_system(){
  debug "Processing preparation commands"
  tkis_prepare

  if [[ $tkis_command == "system" ]] ; then
    tkis_load_list

    list_filename=$LIST_FILE
    unset LIST_FILE
  else
    if [ ! -f ${SY}$tkis_process ] ; then
      tkis_load_list

      list_filename=$LIST_FILE
      unset LIST_FILE
    else
      list_filename=$tkis_process
    fi
  fi

  PR=${PR}$list_filename/

  debug "Saving environmental variables"
  tkis_print_environment

  debug "Executing tkis_command: $tkis_command"
  if [[ $tkis_command == "system" ]] ; then
    tkis_system
  elif [[ $tkis_command == "upgrade" ]] ; then
    tkis_upgrade $tkis_program_name $tkis_program_version $tkis_program_rule
  elif [[ $tkis_command == "execute" ]] ; then
    tkis_single_execution $tkis_program_name $tkis_program_rule
  fi

  # make sure to delete this
  if [[ $tkis_command != "environment" ]] ; then
    rm -f ${tkis_data}environment.$tkis_process
  fi

  if [[ $tkis_command != "upgrade" && $tkis_command != "environment" ]] ; then
    if [[ -e ${tkis_data}installed.$tkis_process && $tkis_remove_install_file == "yes" ]] ; then rm -vf ${tkis_data}installed.$tkis_process ; fi
  fi
}

tkis_system(){
  local start_time_day=
  local start_time_hour=
  local start_time_minute=
  local start_time_second=

  echo
  echo -e "${color_title}Turtle Kevux Installation Scripts${color_reset}"
  echo -e "  ${color_notice}Installing System:${color_reset} ${color_notice}$tkis_process${color_reset}"
  echo

  let start_time_second=$(date --utc +%-S)
  let start_time_minute=$(date --utc +%-M)
  let start_time_hour=$(date --utc +%-H)
  let start_time_day=$(date --utc +%-d)

  local list_size=

  # save original path location
  push_to_null .

  # prepare to execute the rules
  debug "Loading the size of the list $tkis_process from $SY$list_filename"
  list_size=$(fss_basic_list_read -c 0 -s -n $tkis_process $SY$list_filename)

  debug "Loading the list size of $tkis_process for whitespace checks from $SY$list_filename"
  LIST_DATA=$(fss_basic_list_read -c 0 -n $tkis_process $SY$list_filename)

  # now check for non-whitespaces
  if [[ $list_size -le 0 || $LIST_DATA == "" ]] ; then
    error "tkis_system(): There is no data in the list $color_reset$color_notice$tkis_process$color_reset$color_error from the file $color_reset$color_notice$SY$list_filename"
  fi

  # prepare to parse list
  local current=0
  local current_line=
  local current_word=
  local second_word=
  local third_word=
  local fourth_word=
  local fifth_word=
  local version_override="no"

  debug "Checking for system resume file: $tkis_resume"
  if [[ -f $tkis_resume ]] ; then
    current=$(cat $tkis_resume)

    # attempt to identify a corrupt/invalid resume file
    local weird=$(echo $(cat $tkis_resume) | sed -e 's|0||g' -e 's|1||g' -e 's|2||g' -e 's|3||g' -e 's|4||g' -e 's|5||g' -e 's|6||g' -e 's|7||g' -e 's|8||g' -e 's|9||g')

    # on invalid/corrupt data start from the top
    if [[ $current -lt 0 || $current -ge $list_size ]] ; then
      warning "$tkis_resume is $color_reset$color_notice$current$color_reset$color_warning and should be neither < 0 nor >= $list_size. execution will start from the top instead of resuming"
      rm -f $tkis_resume
      current=0
    elif  [[ $weird != "" ]] ; then
      warning "$tkis_resume is $color_reset$color_notice$current$color_reset$color_warning and is corrupt or otherwise invalid. execution will start from the top instead of resuming"
      rm -f $tkis_resume
      current=0
    elif [[ $current == "" ]] ; then
      warning "$tkis_resume is empty; execution will start from the top instead of resuming"
      rm -f $tkis_resume
      current=0
    fi
  fi

  if [ -f ${SE}settings-$list_filename ] ; then
    debug "Loading local settings file: ${SE}settings-$tkis_process"
    tkis_source_file ${SE}settings-$list_filename
  else
    debug "${SE}settings-$list_filename doest not exist or cannot be accessed"
  fi

  # make sure LIST_LINE is reset
  LIST_LINE=

  debug "Looking for ignore system_versions: \"$(fss_basic_list_read -c 0 -n $tkis_process $SY$list_filename  | grep -s '[[:space:]]*ignore system_versions[[:space:]]*$')\""
  if [[ $(fss_basic_list_read -c 0 -n $tkis_process $SY$list_filename  | grep -s -o "^[[:space:]]*ignore system_versions[[:space:]]*$") != "" ]] ; then
    debug "Instructing program to disregard the systems version file"
    tkis_ignore_system_version="yes"
  fi

  debug "Looking for running_on_host: \"$(fss_basic_list_read -c 0 -n $tkis_process $SY$list_filename  | grep -s '^[[:space:]]*runing_on_host[[:space:]]*$')\""
  if [[ $(fss_basic_list_read -c 0 -n $tkis_process $SY$list_filename  | grep -s -o "^[[:space:]]*running_on_host[[:space:]]*$") != "" ]] ; then
    debug "Setting security precautions in place to protect the host system from damage"
    tkis_running_on_host="yes"
    tkis_ignore_system_version="yes"
  fi

  debug "System is resuming/starting on line #$current for the system \"$tkis_process\""
  while [ $current -lt $list_size ] ; do
    debug "obtaining list line #$current, \"$tkis_process\", \"$SY$list_filename\""
    LIST_DATA=$(fss_basic_list_read -c 0 -l $current -n $tkis_process $SY$list_filename)

    debug "obtained: $current_line"
    current_line="$(echo $LIST_DATA | sed -e 's|#.*$||')"
    current_word=$(echo $current_line | awk '{ print $1 }')
    second_word=$(echo $current_line | awk '{ print $2 }')
    third_word=$(echo $current_line | awk '{ print $3 }')
    fourth_word=$(echo $current_line | awk '{ print $4 }')
    fifth_word=$(echo $current_line | awk '{ print $5 }')

    if [[ $current_word == "ignore" || $current_word == "running_on_host" ]] ; then
      if [[ $current_word == "ignore" ]] ; then
        debug "Skipping the reserved word \"ignore\""
      elif [[ $current_word == "running_on_host" ]] ; then
        debug "Skipping the reserved word \"running_on_host\""
      fi
    elif [[ $(echo $current_word | grep -s "^#") == "" && $(echo $current_word | sed -e 's|[[:space:]]||g') != "" ]] ; then

      # specifically allows us to use a specific version and ignore the global or system version
      if [[ $current_word == "specifically" ]] ; then
        version_override=$second_word
        tkis_ignore_system_version="yes"
        debug "Found override ($second_word): $current_word"
        current_line=$(echo $current_line | sed -e "s|^$current_word||g")
        current_line=$(echo $current_line | sed -e "s|^$second_word||g")
        current_word=$(echo $current_line | awk '{ print $1 }')
        second_word=$(echo $current_line | awk '{ print $2 }')
        third_word=$(echo $current_line | awk '{ print $3 }')
        fourth_word=$(echo $current_line | awk '{ print $4 }')
        fifth_word=$(echo $current_line | awk '{ print $5 }')
        debug "Override reset the commands to: $current_word"
      fi

      if [[ $current_word != "repeat" && $current_word != "reinstruct" ]] ; then
        if [[ $third_word == "" ]] ; then
          debug "Now attempting to process: \"$current_line\" at list line #$current_line"
          tkis_package $version_override $(echo $current_line | awk '{ print $2 }') main $current_word
        else
          debug "Now attempting to process: \"$current_line\" at list line #$current_line"
          tkis_package $version_override $(echo $current_line | awk '{ print $2 }') $third_word $current_word $fourth_word $fifth_word
        fi
      else
        if [[ $third_word == "" ]] ; then
          debug "Now attempting to process: \"$current_line\" at list line #$current"
          tkis_package $version_override $(echo $current_line | awk '{ print $2 }') main $current_word $current
        else
          debug "Now attempting to process: \"$current_line\" at list line #$current"
          tkis_package $version_override $(echo $current_line | awk '{ print $2 }') $third_word $current_word $current $fourth_word $fifth_word
        fi
      fi

      if ! [ $? -eq 0 ] ; then
        error "tkis_system(): a problem occured during: tkis_package $color_reset$color_notice$(echo $current_line | awk '{ print $2 }')"
      fi
    elif [[ $(echo $current_word | sed -e 's|[[:space:]]||g') != "" ]] ; then
      debug "\"$current_word\" only contains whitespace, ignoring"
    else
      debug "\"$current_word\" is a comment, ignoring"
    fi

    let current=$current+1

    # reset the override
    version_override="no"

    if [[ $current -lt $list_size ]] ; then
      # save the next spot so resume can work properly
      echo $current > $tkis_resume
    fi
  done

  pop_to_null

  # cleaunup resume rule asits useless now and would only report bad data
  rm -f $tkis_resume
  rm -f ${tkis_data}environment.$list_filename

  tkis_calculate_time
}
