#!/bin/bash

if [ $# -ne 3 ]; then
  echo "Usage: $0 <application> <template_source_dir> <SPEC_dir>"
  exit 1
fi

app=$1
src=$2
dst=$3

# Find spectemplate
if [ ! -f "$src/$app.spec" ]; then
  if [ ! -f "$src/app-template.spec" ]; then
    echo "Source template not found."
    exit 1
  else
    srcfile="$src/app-template.spec"
  fi
else
  srcfile="$src/$app.spec"
fi

# Copy spectemplate to SPECS
cp "$srcfile" "$dst/$app.spec"

# Apply any variables defined in .data
if [ -f "$src/$app.data" ]; then
  srcdata="$src/$app.data"
  source "$srcdata"
  for var in `grep -v -e ^# -e ^\s*$ "$srcdata" | grep = | sed 's/\s*=.*$//'`
  do
    sed -i "s\\@${var}@\\${!var}\\g" "$dst/$app.spec"
  done
fi

