#!/bin/bash

# Config.mk.in から Config.mk を生成するスクリプト

# デフォルトのインストール先を設定
prefix=`pwd`

# 設定変数を定義
FC="${FC:-spmfrt}"
FCFLAGS="${FCFLAGS:-}"
LDFLAGS="${LDFLAGS:-}"
LDLIBS="${LDLIBS:-}"
CPPFLAGS="${CPPFLAGS:-}"
MODSUFFIX="${MODSUFFIX:-mod}"
MODPATHFLAG="${MODPATHFLAG:--I}"
DCPAMLIBNAME="${DCPAMLIBNAME:-dcpam6}"

# ヘルプメッセージを表示する関数
show_help() {
    cat << EOF
Usage: $0 [OPTIONS]

Configure script to generate Config.mk from Config.mk.in.

Options:
  --help               Display this help and exit.
  --prefix=DIR         Install files in DIR [/usr/local/dcpam6].
  --enable-mpi         Enable MPI support. Adds -DLIB_MPI to CPPFLAGS.

Environment Variables:
  FC                   Specify spmfrt script for SPML ver.2.0 [spmfrt]
  FCFLAGS              Fortran compiler flags (e.g., -g -O0).
  CPPFLAGS             C preprocessor flags.
  LDFLAGS              Linker flags.
  LDLIBS               Linker flags for specifying link libraries.
  MODSUFFIX            Fortran module file suffix [mod]
  MODPATHFLAG          Fortran module file path flag [-I]
  DCPAMLIBNAME	       DCPAM6 Library name [dcpam6]

Example:
  ./configure --prefix=/opt/my-app FC=/opt/my-app/spml2/spmfrt FCFLAGS="-g -fbacktrace"
  
EOF
}


# 引数を解析
for arg in "$@"; do
  case $arg in
    --help)
      show_help
      exit 0
      ;;
    --prefix=*)
      prefix="${arg#*=}"
      ;;
    --enable-mpi)
      # --enable-mpi が指定された場合、CPPFLAGS に -DLIB_MPI を追加
      CPPFLAGS="$CPPFLAGS -DLIB_MPI"
      ;;
    *)
      echo "Warning: Unknown option '$arg'. Ignoring."
      ;;
  esac
done

# Config.mk.in が存在するか確認
if [ ! -f "Config.mk.in" ]; then
    echo "Error: Config.mk.in not found!"
    exit 1
fi

echo "Creating Config.mk from Config.mk.in..."

# Config.mk.in の内容を読み込み、変数を置き換えて Config.mk に出力
sed -e "s!@prefix@!$prefix!g" \
    -e "s!@FC@!$FC!g" \
    -e "s!@FCFLAGS@!$FCFLAGS!g" \
    -e "s!@LDFLAGS@!$LDFLAGS!g" \
    -e "s!@LDLIBS@!$LDLIBS!g" \
    -e "s!@CPPFLAGS@!$CPPFLAGS!g" \
    -e "s!@MODSUFFIX@!$MODSUFFIX!g" \
    -e "s!@MODPATHFLAG@!$MODPATHFLAG!g" \
    -e "s!@DCPAMLIBNAME@!$DCPAMLIBNAME!g" \
  Config.mk.in > Config.mk

echo "Done."
