#!/usr/bin/env bash

# Copyright © 2012-2026 ScriptFanix
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# This program 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 General Public License for more details.

# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.

upgradedatabase_1_2() {
	local	data		\
		datas		\
		id		\
		rename_pattern	\
		pattern		\
		fat32
	echo "Upgrading database to version 2... (backup is $database.bak_v1)"
	cp "$database" "$database.bak_v1"
	# Add new columns to hold the fat32compat and ascii settings separately
	echo 'ALTER TABLE destination_files ADD COLUMN fat32compat INTEGER;' >&3
	echo 'ALTER TABLE destination_files ADD COLUMN ascii INTEGER;' >&3
	# Read all existing destination_files rows to migrate rename_pattern format
	# Old format embedded fat32compat after a colon: "pattern:fat32value"
	echo '
SELECT		id,
		rename_pattern
FROM		destination_files;

SELECT	"AtOM::NoMoreData";' >&3

	read -u4 -r -d $'\0' data
	while [[ $data != AtOM::NoMoreData ]]
	do
		datas+=( "$data" )
		read -u4 -r -d $'\0' data
	done
	# Ensure consistency by performing all updates in a single transaction
	echo 'BEGIN TRANSACTION;' >&3
	for data in "${datas[@]}"
	do
		id="${data%%::AtOM:SQL:Sep::*}"
		rename_pattern="${data#*::AtOM:SQL:Sep::}"
		# Split "pattern:fat32" on the colon separator
		IFS=':'
		read pattern fat32 <<<"$rename_pattern"
		IFS="$oldIFS"
		# ASCII-only didn't exist in v1; default to off
		Update destination_files		\
			rename_pattern	"$pattern"	\
			fat32compat	"$fat32"	\
			ascii		0		\
		<<<"id = $id"
	done
	echo 'COMMIT;' >&3
	Update atom version 2 <<<"1 = 1"
}
