#!/bin/bash

if [[ ${1} == "debug" ]]; then
  debugmode=true
elif [[ ${1} == "run" ]]; then
  debugmode=false
else
  echo "Must be executed in run mode or debug mode!" >&2
  echo "Example:" >&2
  echo "  $0 run" >&2
  echo "or:" >&2
  echo "  $0 debug" >&2
  exit 1
fi

totalsteps=$(wc -l < own.sh)
newhash="$(md5sum own.sh)"

if [[ $? != 0 ]]; then
  echo "Install dependancy md5sum..." >&2
  exit 2
fi

newhash="${newhash:0:32}"
aptcount=0
maxaptcount=1
rm -f own.temp

if [[ -f step.step ]]; then
  source step.step
else
  currentstep=1
  hash="${newhash}"
fi

if [[ "${hash}" != "${newhash}" ]]; then
  echo "own.sh has been changed! Restarting from step 1..."
  currentstep=1
  hash="${newhash}"
fi

for ((step=${currentstep}; step<=${totalsteps}; step++)); do
  line="$(head -n ${step} own.sh | tail -1)"

  if [[ ${step} == ${currentstep} ]]; then
    echo -n "Line ${step}"
  fi

  if [[ -n ${line} ]]; then
    while [[ ${line:0:1} == " " ]]; do
      line="${line:1}"
    done

    if [[ ${line:0:6} == "apt -y" ]]; then
      ((aptcount++))
    elif [[ ${line:0:6} == "reboot" ]]; then
      line="#${line}"
    fi
  fi

  if [[ ${aptcount} -lt ${maxaptcount} ]]; then
    echo "${line}" >> own.temp
  else
    if [[ ${step} -gt ${currentstep} ]]; then
      echo -n " to ${step}"
    fi

    echo " of ${totalsteps}"
    echo "${line}" >> own.temp

    if [[ ${debugmode} == true ]]; then
      echo "The following code from own.sh would have been executed..."
      cat own.temp
    else
      echo "The following code from own.sh will be executed..."
      cat own.temp
      delay=$(($(wc -l < own.temp)/4+3))
      echo -n "Executing in ${delay} seconds"

      for ((d=0; d<${delay}; d++)); do
        sleep 1
        echo -n "."
      done

      echo
      echo
      echo
      echo
      source own.temp
    fi

    rm -f own.temp
    echo "currentstep=$((step+1))" > step.step
    echo "hash=\"${hash}\"" >> step.step

    exit
  fi
done

if [[ ${step} -gt ${currentstep} ]]; then
  echo -n " to ${step}"
fi

echo " of ${totalsteps}"

if [[ ${debugmode} == true ]]; then
  echo "The following code from own.sh would have been executed..."
  cat own.temp
else
  echo "The following code from own.sh will be executed..."
  cat own.temp
  delay=$(($(wc -l < own.temp)/4+3))
  echo -n "Executing in ${delay} seconds"

  for ((d=0; d<${delay}; d++)); do
    sleep 1
    echo -n "."
  done

  echo
  echo
  echo
  echo
  source own.temp
fi

rm -f own.temp
echo "End of own.sh has been reached..."
rm -f step.step

exit
