#!/usr/bin/env sh
set -eu

MODE=${1:-}
HOST_NAME=${HOST_NAME:-localhost}
PORT=${PORT:-3306}
DATABASE=${DATABASE:-SALECULATOR}
DB_USER=${DB_USER:-saleculator}
DB_PASSWORD=${DB_PASSWORD:-}
CONFIG_FILE=${CONFIG_FILE:-"$HOME/Saleculator.properties"}

usage() {
  cat <<EOF
Usage:
  $0 local
  $0 network HOST [DATABASE] [USER]
  $0 test HOST [DATABASE] [USER]

Environment:
  DB_PASSWORD     Saleculator database password
  ROOT_USER       MySQL admin user, default root
  ROOT_PASSWORD   MySQL admin password
  CONFIG_FILE     Config path, default ~/Saleculator.properties
  ALLOW_REMOTE_CLIENTS=true creates local DB user for network clients
EOF
}

mysql_cmd() {
  command -v mysql >/dev/null 2>&1 || {
    echo "mysql client was not found. Install mysql-client." >&2
    exit 127
  }
  MYSQL_PWD=$1 mysql --host="$2" --port="$3" --user="$4" --protocol=tcp --batch --silent ${5:+"$5"}
}

write_prop() {
  key=$1
  value=$2
  file=$3
  tmp="$file.tmp.$$"
  mkdir -p "$(dirname "$file")"
  [ -f "$file" ] || cp "$(dirname "$0")/../config/Saleculator.properties.sample" "$file"
  if grep -q "^[[:space:]]*$key[[:space:]]*=" "$file"; then
    sed "s|^[[:space:]]*$key[[:space:]]*=.*|$key=$value|" "$file" > "$tmp"
  else
    cp "$file" "$tmp"
    printf '%s=%s\n' "$key" "$value" >> "$tmp"
  fi
  mv "$tmp" "$file"
}

write_db_config() {
  host=$1
  database=$2
  user=$3
  password=$4
  jdbc="jdbc\\:mysql\\://$host\\:$PORT/$database?characterEncoding\\=utf8"
  write_prop "db.URL" "$jdbc" "$CONFIG_FILE"
  write_prop "db.user" "$user" "$CONFIG_FILE"
  write_prop "db.password" "$password" "$CONFIG_FILE"
  write_prop "db.driver" "com.mysql.jdbc.Driver" "$CONFIG_FILE"
  write_prop "db.driverlib" "./lib/mysql-connector-java-5.1.7-bin.jar" "$CONFIG_FILE"
}

case "$MODE" in
  local)
    ROOT_USER=${ROOT_USER:-root}
    ROOT_PASSWORD=${ROOT_PASSWORD:-}
    [ -n "$DB_PASSWORD" ] || { printf 'Password for Saleculator database user %s: ' "$DB_USER"; stty -echo; read DB_PASSWORD; stty echo; printf '\n'; }
    [ -n "$ROOT_PASSWORD" ] || { printf 'MySQL admin password for %s: ' "$ROOT_USER"; stty -echo; read ROOT_PASSWORD; stty echo; printf '\n'; }
    CLIENT_HOST=localhost
    [ "${ALLOW_REMOTE_CLIENTS:-false}" = "true" ] && CLIENT_HOST=%
    mysql_cmd "$ROOT_PASSWORD" localhost "$PORT" "$ROOT_USER" <<SQL
CREATE DATABASE IF NOT EXISTS \`$DATABASE\` CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER IF NOT EXISTS '$DB_USER'@'$CLIENT_HOST' IDENTIFIED BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON \`$DATABASE\`.* TO '$DB_USER'@'$CLIENT_HOST';
FLUSH PRIVILEGES;
SQL
    write_db_config localhost "$DATABASE" "$DB_USER" "$DB_PASSWORD"
    echo "Local database configured. Start Saleculator and approve database creation when prompted."
    ;;
  network)
    HOST_NAME=${2:?Database host is required}
    DATABASE=${3:-$DATABASE}
    DB_USER=${4:-$DB_USER}
    [ -n "$DB_PASSWORD" ] || { printf 'Password for Saleculator database user %s: ' "$DB_USER"; stty -echo; read DB_PASSWORD; stty echo; printf '\n'; }
    write_db_config "$HOST_NAME" "$DATABASE" "$DB_USER" "$DB_PASSWORD"
    echo "Network client database configuration saved: $CONFIG_FILE"
    ;;
  test)
    HOST_NAME=${2:-$HOST_NAME}
    DATABASE=${3:-$DATABASE}
    DB_USER=${4:-$DB_USER}
    [ -n "$DB_PASSWORD" ] || { printf 'Password for Saleculator database user %s: ' "$DB_USER"; stty -echo; read DB_PASSWORD; stty echo; printf '\n'; }
    echo "SELECT 1;" | mysql_cmd "$DB_PASSWORD" "$HOST_NAME" "$PORT" "$DB_USER" "$DATABASE" >/dev/null
    echo "Database connection OK: $HOST_NAME:$PORT/$DATABASE"
    ;;
  *)
    usage
    exit 2
    ;;
esac
