#! /bin/sh

#---------------------------------------------------------------------
#                           chicken and egg                           
#---------------------------------------------------------------------

which perl >/dev/null 2>/dev/null || {
  echo "fw-bootstrap: fatal: can't locate perl" 1>&2
  exit 1
}

if test -z "${FW_ROOT}"
  then
    FW_ROOT=`echo "$0" | perl -pe 's%bin//?fw-bootstrap$%%;'`
    export FW_ROOT
  fi

test -e fw || ln -sf "${FW_ROOT}/share/fw" . || {
  echo "fw-bootstrap: fatal: can't link fw directory" 1>&2
  exit 1
}

test -f "fw/sh/fw-find.sh" && fws="fw/sh/fw-find.sh"
test -f "fw.local/sh/fw-find.sh" && fws="fw.local/sh/fw-find.sh"
test ! -z "$fws" || {
  echo "fw-bootstrap: fatal: can't locate fw-find.sh" 1>&2
  exit 1
}

. "$fws"

#---------------------------------------------------------------------
#                              routines
#---------------------------------------------------------------------

fw_source "fw-bootstrap" "sh/detect-revision.sh"
fw_source "fw-bootstrap" "sh/fatal.sh"
fw_source "fw-bootstrap" "sh/parse-args.sh"
fw_source "fw-bootstrap" "sh/validate-args.sh"
fw_source "fw-bootstrap" "sh/fw-exec.sh"

base_bootstrap () \
  {
    cat <<EOD > create-package || fatal "fw-bootstrap"
#! /bin/sh

# DO NOT EDIT THIS FILE.  It is autogenerated by bootstrap.

if test -d bin
  then
    PATH="\`pwd\`/bin:\$PATH"
  fi

if test -d fw/bin
  then
    PATH="\`pwd\`/fw/bin:\$PATH"
    export PATH
  fi

fwp=\`which fw-package\`

if test -z "\$fwp"
  then
    echo "create-package: fatal: fw-package not installed or not in PATH" 1>&2
    exit 1
  fi

"\$fwp" $@ "\$@"
EOD

    chmod +x create-package || fatal "fw-bootstrap"

    fw_exec "revision/$revision/ignore-files" create-package ||         \
    fatal "fw-bootstrap"
  }

run_bootstrap () \
  {
    fw_exec "template/$template/bootstrap" "$@" || {
      echo "fw-bootstrap: error: bootstrap failed" 1>&2
      fatal
    }
  }

#---------------------------------------------------------------------
#                                main                                 
#---------------------------------------------------------------------

parse_args "fw-bootstrap" "$@"

test -z "$help" || {
  echo "usage: fw-bootstrap [ --trace ] --template template" 1>&2
  exit 0
}

validate_args "fw-bootstrap" "name template" "template"

test -n "$revision" || detect_revision revision || fatal "fw-bootstrap"

base_bootstrap "$@" --revision "$revision"

test ! -z "$baseonly" || run_bootstrap "$@" --revision "$revision"
