#!/bin/bash
# This file is part of GNU TALER.
# Copyright (C) 2025 Taler Systems SA
#
# TALER is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free Software
# Foundation; either version 2.1, or (at your option) any later version.
#
# TALER is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along with
# TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
#
# @author Antoine d'Aligny

# Error checking on
set -eu

# 1 is true, 0 is false
RESET_DB=0
FORCE_PERMS=0
SKIP_INIT=0
DBUSER="taler-cyclos-httpd"
DBGROUP="taler-cyclos-db"
CFGFILE="/etc/taler-cyclos/taler-cyclos.conf"

# Parse command-line options
while getopts 'c:g:hprsu:' OPTION; do
  case "$OPTION" in
  c)
    CFGFILE="$OPTARG"
    ;;
  g)
    DBGROUP="$OPTARG"
    ;;
  h)
    echo 'Supported options:'
    echo "  -c FILENAME  -- use configuration FILENAME (default: $CFGFILE)"
    echo "  -g GROUP     -- taler-cyclos to be run by GROUP (default: $DBGROUP)"
    echo "  -h           -- print this help text"
    echo "  -r           -- reset database (dangerous)"
    echo "  -p           -- force permission setup even without database initialization"
    echo "  -s           -- skip database initialization"
    echo "  -u USER      -- taler-cyclos to be run by USER (default: $DBUSER)"
    exit 0
    ;;
  p)
    FORCE_PERMS="1"
    ;;
  r)
    RESET_DB="1"
    ;;
  s)
    SKIP_INIT="1"
    ;;
  u)
    DBUSER="$OPTARG"
    ;;
  ?)
    echo "Unrecognized command line option '$OPTION'" 1 &>2
    exit 1
    ;;
  esac
done

function exit_fail() {
  echo "$@" >&2
  exit 1
}

if ! id postgres >/dev/null; then
  exit_fail "Could not find 'postgres' user. Please install Postgresql first"
fi

if ! taler-cyclos --version 2>/dev/null; then
  exit_fail "Required 'taler-cyclos' not found. Please fix your installation."
fi

if [ "$(id -u)" -ne 0 ]; then
  exit_fail "This script must be run as root"
fi

# Check OS users exist
if ! id "$DBUSER" >/dev/null; then
  exit_fail "Could not find '$DBUSER' user. Please set it up first"
fi

# Create DB user matching OS user name
echo "Setting up database user '$DBUSER'." 1>&2
if ! sudo -i -u postgres createuser "$DBUSER" 2>/dev/null; then
  echo "Database user '$DBUSER' already existed. Continuing anyway." 1>&2
fi

# Check database name
DBPATH=$(taler-cyclos -c "$CFGFILE" config get cyclosdb-postgres CONFIG)
if ! echo "$DBPATH" | grep "postgres://" >/dev/null; then
  exit_fail "Invalid database configuration value '$DBPATH'." 1>&2
fi
DBNAME=$(echo "$DBPATH" | sed -e "s/postgres:\/\/.*\///" -e "s/?.*//")

# Reset database
if sudo -i -u postgres psql "$DBNAME" </dev/null 2>/dev/null; then
  if [ 1 = "$RESET_DB" ]; then
    echo "Deleting existing database '$DBNAME'." 1>&2
    if ! sudo -i -u postgres dropdb "$DBNAME"; then
      exit_fail "Failed to delete existing database '$DBNAME'"
    fi
    DO_CREATE=1
  else
    echo "Database '$DBNAME' already exists, continuing anyway."
    DO_CREATE=0
  fi
else
  DO_CREATE=1
fi

# Create database
if [ 1 = "$DO_CREATE" ]; then
  echo "Creating database '$DBNAME'." 1>&2
  if ! sudo -i -u postgres createdb -O "$DBUSER" "$DBNAME"; then
    exit_fail "Failed to create database '$DBNAME'"
  fi
fi

# Run dbinit
if [ 0 = "$SKIP_INIT" ]; then
  echo "Initialize database schema"
  if ! sudo -u "$DBUSER" taler-cyclos dbinit -c "$CFGFILE"; then
    exit_fail "Failed to initialize database schema"
  fi
fi

# Set permission for group user
if [ 0 = "$SKIP_INIT" ] || [ 1 = "$FORCE_PERMS" ]; then
  # Create DB group matching OS group name
  echo "Setting up database group '$DBGROUP'." 1>&2
  if ! sudo -i -u postgres createuser "$DBGROUP" 2>/dev/null; then
    echo "Database group '$DBGROUP' already existed. Continuing anyway." 1>&2
  fi
  if ! sudo -i -u postgres psql "$DBNAME" <<-EOF
    GRANT ALL ON SCHEMA cyclos TO "$DBGROUP";
    GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA cyclos TO "$DBGROUP";
EOF
  then
      exit_fail "Failed to grant access to '$DBGROUP'."
  fi

  # Update group users rights
  DB_GRP="$(getent group "$DBGROUP" | sed -e "s/.*://g" -e "s/,/ /g")"
  echo "Initializing permissions for '$DB_GRP' users." 1>&2
  for GROUPIE in $DB_GRP; do
    if [ "$GROUPIE" != "$DBUSER" ]; then
      if ! sudo -i -u postgres createuser "$GROUPIE" 2>/dev/null; then
        echo "Database user '$GROUPIE' already existed. Continuing anyway." 1>&2
      fi
    fi
    
    if ! echo "GRANT \"$DBGROUP\" TO \"$GROUPIE\"" |
      sudo -i -u postgres psql "$DBNAME"; then
      exit_fail "Failed to make '$GROUPIE' part of '$DBGROUP' db group."
    fi
  done
fi

echo "Database configuration finished." 1>&2
