#!/bin/bash
# Contains the spell installation functions, as specified on sourcemage.org
# backgrounding version

# NEEDS: a /var/state/sorcery/depends containing all depends between
#        spells that could be installed
#        a /var/state/sorcery/packages containing all spells that could
#        get installed and their versions
#        /var/state/smgl.install/conflicts containing lines of the form
#        spell;conflicts_with

# --------------public----------------------

SI_QUEUE_DIR=/tmp/spellinstall
SI_SPELL_QUEUE=$SI_QUEUE_DIR/queue
SI_CONFLICTS=$SI_QUEUE_DIR/conflicts
SI_INSTALLING=$SI_QUEUE_DIR/installing


# Marks a spell for installation. Does not install it.
# args: the spells
si_queue() {
  mkdir -p ${SI_QUEUE_DIR}
  >$SI_QUEUE_DIR/tmpqueue
  >$SI_QUEUE_DIR/tmpqueue.unloop

  recursively_make_queue $SI_QUEUE_DIR/tmpqueue "$@"

  si_run_conflicts $(cat $SI_QUEUE_DIR/tmpqueue)

  lock_resource SI_SPELL_QUEUE
  # Resource is called SI_SPELL_QUEUE, not $SI_SPELL_QUEUE
  cat $SI_QUEUE_DIR/tmpqueue >>${SI_SPELL_QUEUE}
  unlock_resource SI_SPELL_QUEUE

  rm -f $SI_QUEUE_DIR/tmpqueue $SI_QUEUE_DIR/tmpqueue.unloop
}

# inserts a spell and its dependencies at the top of the spell queue
# args: the spells to install
si_queue_now() {
  mkdir -p ${SI_QUEUE_DIR}
  >$SI_QUEUE_DIR/tmpqueue
  >$SI_QUEUE_DIR/tmpqueue.unloop

  recursively_make_queue $SI_QUEUE_DIR/tmpqueue "$@"

  si_run_conflicts $(cat $SI_QUEUE_DIR/tmpqueue)

  lock_resource SI_SPELL_QUEUE
  cat $SI_SPELL_QUEUE >>$SI_QUEUE_DIR/tmpqueue # The other way around here
  mv $SI_QUEUE_DIR/tmpqueue $SI_SPELL_QUEUE
  unlock_resource SI_SPELL_QUEUE

  rm -f $SI_QUEUE_DIR/tmpqueue.unloop
}

# marks a spell for installation and does not return until it is installed
# args: the spells to install
si_wait() {
  si_queue_now "$@"
  local spell
  for spell in "$@" ;do
    si_query $spell
    while [[ $? != 3 ]] ;do
      echo -en '\r\033[2K'
      echo -n "waiting for $spell... (now installing $(cat $SI_INSTALLING))"
      test -e $SI_QUEUE_DIR/debug && touch $SI_QUEUE_DIR/force_run
      sleep 1
      si_query $spell
    done
    echo -en '\r\033[2K'
    echo "done  with  $spell."
  done
  true
}

# Returns 1 if the spell is queued, 2 if it is getting installed,
# 3 if it is installed, 10 if it would conflict with a queued/installed spell
# 0 (true) otherwise
# $1: the spell
si_query() {
  touch $SI_INSTALLING $SI_SPELL_QUEUE $SI_CONFLICTS

  if si_get_fake_spell "$1" ;then
    return 3
  elif grep -q "^$1:" ${TARGET}/var/state/sorcery/packages ;then
    return 3
  elif grep -q "^$1$" $SI_INSTALLING ;then
    return 2
  elif grep -q "^$1$" $SI_SPELL_QUEUE ;then
    return 1
  elif grep -q "^$1$" $SI_CONFLICTS ;then
    return 10
  else
    return 0
  fi
}

# Casts all spells remaining in the queue
# no arguments
si_flush() {
  echo "Waiting for all spells left to complete..."
  while [ -s $SI_SPELL_QUEUE ] ;do
    test -e $SI_QUEUE_DIR/debug && touch $SI_QUEUE_DIR/force_run
    echo -en '\r\033[2K'
    echo -n "installing $(cat $SI_INSTALLING)..."
    sleep 1
  done
}

# Casts top of queue and removes it
# no arguments
si_pop() {
  if test -s $SI_SPELL_QUEUE ;then
    spell=$(head -n 1 $SI_SPELL_QUEUE)
    si_install_spell "$spell" ||
    debug_log "ERROR" -1 "Failed to install $spell"
    lock_resource SI_SPELL_QUEUE
    sed -i "/^$spell$/d" $SI_SPELL_QUEUE
    unlock_resource SI_SPELL_QUEUE
    return 0
  else
    return 1
  fi
}

# --------------private-------------------

# Cycles down the dependency tree, puts the spell and its dependencies
# sorted dependency-first into a file
# args: $1: filename to put the queue in
# Internally uses $1.unloop as file to check for loops - make sure
# it exists and is empty before calling
recursively_make_queue() {
  local spell
  local queue=$1
  shift
  for spell in "$@" ;do
    if ! grep -q "^$spell$" $queue.unloop ;then
      echo "$spell" >>$queue.unloop
      # No spell gets handled twice, => no infinite loops on circular deps
      recursively_make_queue $queue $( si_get_dependencies $spell )
      echo "$spell" >>$queue
    fi
  done
}

# Our own conflicts handling.
# Quite cheap, but ought to do its job.
# $1: spell to check conflicts of.
# Appends any conflicts found to the end of $SI_CONFLICTS.

function si_run_conflicts() {
  local spell
  for spell in "$@" ;do
    grep "^$spell:" $STATE_DIR/conflicts |
      cut -d':' -f2 >>$SI_CONFLICTS
  done
}

# Cheapo checking dependencies.
# Echos any spells that $1 directly depends on

si_get_dependencies() {
  grep "^$1:[^:]*:on:" /var/state/sorcery/depends |
  cut -d: -f2 |
  sed 's/(.*$//' # cut j2sdk-bin(JAVA) to j2sdk-bin
}

# If we want any (backgrounded) action filed like a spell.
# Fake spells should be calles "Iso.<name>",
# we hope no real spell has the same name.

# Returns true when $1 is a fake spell
si_is_fake_spell() {
  [[ "$1" == Iso.* ]]
}

# Return true when the given fake spell is "installed"
si_get_fake_spell() {
  case $1 in
    "Iso.Caches")
                 check_dependency install_caches
               ;;
    "Iso.Basics")
                 check_dependency basic_system
               ;;
    "Iso.Compile_env")
                      check_dependency compile_system
                    ;;
    Iso.*)
          return 0
        ;;
    *)
      return 1
    ;;
  esac
}

si_run_fake_spell() {
  debug_log "spellinstall" 2 "installing fake spell $1"
  case $1 in
    "Iso.Caches")
                 local TOTALFILES=`ls -1 /var/cache/sorcery | wc -l`
                 local file
                 for file in /var/cache/sorcery/* ; do
                   # Sacrifice some performance for prettiness ;-)
                   cp --parents $file ${TARGET}
                   echo $file
                 done |
                   progress_bar $TOTALFILES "Installing Source Caches..." \
                    "Installing Source Cache" "Installing"
                 fill_dependency install_caches
               ;;
    "Iso.Basics")
                 fill_dependency basic_system
               ;;
    "Iso.Compile_env")
                      check_dependency compile_system ||
                      try_run -q chroot_cmd scribe reindex
                      fill_dependency compile_system
                    ;;
    Iso.*)
          return 0
        ;;
    *)
      return 1
    ;;
  esac
}

# Theses functions solely exists to quickfix spells that don't work properly
# $1: spell to install
si_pre_workaround() {
  case $1 in
    "example")
              try_run -q cp ${TARGET}/etc/passwd /tmp/backuppass
            ;;
  esac
}

si_post_workaround() {
  case $1 in
       "bash")
              try_run -q cp --parents -a /etc/profile* $TARGET
            ;;
    "example")
              try_run -q cp /tmp/backuppass ${TARGET}/etc/passwd
              try_run -q chroot_cmd mk_example_key
            ;;
    "openssh")
              try_run -q rm -f ${TARGET}/etc/ssh/*host*
              try_run -q chroot_cmd \
                  ssh-keygen -t rsa1 -f /etc/ssh/ssh_host_key     -N ""
              try_run -q chroot_cmd \
                  ssh-keygen -t rsa  -f /etc/ssh/ssh_host_rsa_key -N ""
              try_run -q chroot_cmd \
                  ssh-keygen -t dsa  -f /etc/ssh/ssh_host_dsa_key -N ""
            ;;
      "gnupg")
              try_run -q mkdir -p -m 700 $TARGET/root/.gnupg
            ;;
"netkit-base")
              try_run -q sed -i \
              "s/^127.0.0.1.*/127.0.0.1	localhost	$(cat /etc/hostname)/" \
              $TARGET/etc/hosts
            ;;
  esac
}

# $1: the spell to install
si_install_spell() {

  debug_log "spellinstall" 2 "considering to install $1"

  if si_is_fake_spell $1 ;then
    echo "$1" >$SI_INSTALLING
    si_run_fake_spell $1
    local rc=$?
    >$SI_INSTALLING # Clear file
    return $rc #nothing left to do
  fi

  if grep -q "^$1:" ${TARGET}/var/state/sorcery/packages ;then
    debug_log "spellinstall" 3 "discarding $1 as already installed"
    return 0 #already installed
  fi

  echo "Installing $1..." >&2
  debug_log "spellinstall" 2 "starting install of $1"
  echo "$1" >$SI_INSTALLING

  # TODO: The backgrounded version should be locking now,
  #       and logging the current spell
  debug_log "spellinstall" 3 "running pre_workaround for $1"
  si_pre_workaround $1                                     &&

  local VERSION=$(grep "^$1:" /var/state/sorcery/packages | cut -d: -f4) &&
  if [ -z $VERSION ] ;then
    echo "The spell $1 does not seem to be on this CD!?" >&2
    debug_log "ERROR" -1 "Not finding spell $1"
    return 1
  fi                                                       &&
  # TODO: I don't like using *'s
  debug_log "spellinstall" 3 "installing files for $1"     &&
  try_run -q tar -xjp -C ${TARGET} -f \
      /var/cache/sorcery/$1-${VERSION}-*.tar.bz2 &&
  if [[ "$1" != "smgl-fhs" ]] ;then
    debug_log "spellinstall" 3 "ldconfig for $1"           &&
    try_run -q chroot_cmd /sbin/ldconfig
  fi                                                       &&

  try_run -q echo "$1:$(date +%Y%m%d):installed:${VERSION}" \
    >>${TARGET}/var/state/sorcery/packages                 &&

  debug_log "spellinstall" 3 "post_workaround for $1"      &&
  si_post_workaround $1                                    &&

  debug_log "spellinstall" 1 "successfully installed $1"   &&
  >$SI_INSTALLING # Clear file
}
