#!/bin/bash

set -e
set -u

APPSTORE_HOME=$(cd $(dirname "$0")/.. && pwd)

. $APPSTORE_HOME/lib/common
# HEADER END

conf_get() {
  name=$1; shift
  var=$1; shift
  value=$(app cat-conf -f "$APPSTORE/appstore.config" -k "$var" | cut -f 2- -d =)
  eval ${name}='${value}'
}

check_app() {
  local app=$1; shift

  dir=$app
  conf_get resolver "${app}.resolver"
  conf_get resolver_args "${app}.resolver_args"
  conf_get version "${app}.version"
  conf_get state "${app}.state"

  if [[ -z $resolver ]] || [[ -z $resolver_args ]] || [[ -z $version ]] || [[ -z $state ]]
  then
    echo "$app: invalid configuration, missing one of ${app}.resolver, ${app}.resolver_args, ${app}.version, ${app}.state"
    return
  fi

  cd "$APPSTORE"

  if [[ -d $dir ]]
  then
    cd "$dir"
    dir=`pwd`

    if [[ -r $APPSTORE/$app.config ]]
    then
      app conf import $APPSTORE/$app.config
    fi
    app conf set app.version "$version"
    app upgrade
  else
    echo "$dir: new app"
    if [[ -r ${dir}.config ]]
    then
      append_config="${dir}.config"
    fi

    app init \
      ${append_config:+-c} $append_config \
      -d "$dir" \
      "$resolver" "$resolver_args"
    cd "$dir"
    dir=`pwd`
  fi

  cd "$dir"

  if [[ $state = enabled ]]
  then
    app start || true
  else
    app stop || true
  fi
}

REPO="$1"; shift
APPSTORE="$1"; shift

make_absolute REPO
make_absolute APPSTORE

cd "$APPSTORE"

# This should probably be a git fetch && checkout origin/HEAD --force
# or whatever.
git pull -q "$REPO" master

conf_get apps appstore.apps
apps=$(echo "$apps" | sed "s/, */,/g")

IFS=,
for app in $apps
do
  if [[ $app = "" ]]
  then
    continue
  fi

  assert_valid_app_name "$app"

  check_app "$app" || true
done

echo "Done."