#!/usr/bin/env bash
set -euo pipefail

### Correct permissions for romm data directories

APP_DIR="$(readlink -f "$(dirname "${BASH_SOURCE[0]}")/..")"
APP_DATA_DIR="${APP_DIR}/data"

DESIRED_OWNER="1000:1000"

CONFIG_DATA_DIR="${APP_DATA_DIR}/config"

romm_correct_permission() {
	local -r path="${1}"

	if [[ -d "${path}" ]]; then
		owner=$(stat -c "%u:%g" "${path}")

		if [[ "${owner}" != "${DESIRED_OWNER}" ]]; then
			chown "${DESIRED_OWNER}" "${path}"
		fi
	fi
}

### Create default configuration file for romm if it does not exist

ROMM_CONFIG_FILE="${CONFIG_DATA_DIR}/config.yml"

# We check if the romm config file does not exist
if [[ ! -f "${ROMM_CONFIG_FILE}" ]]; then
  echo "Creating romm configuration file."
  # Create the romm configuration file
  cat >"${ROMM_CONFIG_FILE}" <<'EOF'
exclude:
  # Exclude platforms to be scanned
  platforms: [] # ['my_excluded_platform_1', 'my_excluded_platform_2']

  # Exclude roms or parts of roms to be scanned
  roms:
    # Single file games section.
    # Will not apply to files that are in sub-folders (multi-disc roms, games with updates, DLC, patches, etc.)
    single_file:
      # Exclude all files with certain extensions to be scanned
      extensions: [] # ['xml', 'txt']

      # Exclude matched file names to be scanned.
      # Supports unix filename pattern matching
      # Can also exclude files by extension
      names: [] # ['info.txt', '._*', '*.nfo']

    # Multi files games section
    # Will apply to files that are in sub-folders (multi-disc roms, games with updates, DLC, patches, etc.)
    multi_file:
      # Exclude matched 'folder' names to be scanned (RomM identifies folders as multi file games)
      names: [] # ['my_multi_file_game', 'DLC']

      # Exclude files within sub-folders.
      parts:
        # Exclude matched file names to be scanned from multi file roms
        # Keep in mind that RomM doesn't scan folders inside multi files games,
        # so there is no need to exclude folders from inside of multi files games.
        names: [] # ['data.xml', '._*'] # Supports unix filename pattern matching

        # Exclude all files with certain extensions to be scanned from multi file roms
        extensions: [] # ['xml', 'txt']

system:
  # Asociate different platform names to your current file system platform names
  # [your custom platform folder name]: [RomM platform name]
  # In this example if you have a 'gc' folder, RomM will treat it like the 'ngc' folder and if you have a 'psx' folder, RomM will treat it like the 'ps' folder
  platforms: {} # { gc: 'ngc', psx: 'ps' }

  # Asociate one platform to it's main version
  versions: {} # { naomi: 'arcade' }

# The folder name where your roms are located
filesystem: {} # { roms_folder: 'roms' } For example if your folder structure is /home/user/library/roms_folder
EOF

echo "Created romm configuration file."

romm_correct_permission "${CONFIG_DATA_DIR}"

fi
