#!/bin/sh

# Copyright (C) 2023-2025 Internet Systems Consortium, Inc. ("ISC")
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

# Exit with error if commands exit with non-zero and if undefined variables are
# used.
set -eu

# shellcheck disable=SC2034
# SC2034: ... appears unused. Verify use (or export if used externally).
prefix="@prefix@"

# Include utilities based on location of this script. Check for sources first,
# so that the unexpected situations with weird paths fall on the default
# case of installed.
script_path=$(cd "$(dirname "${0}")" && pwd)
if test "${script_path}" = "@abs_top_builddir@/src/share/database/scripts/mysql"; then
    # shellcheck source=./src/bin/admin/admin-utils.sh.in
    . "@abs_top_builddir@/src/bin/admin/admin-utils.sh"
else
    # shellcheck source=./src/bin/admin/admin-utils.sh.in
    . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh"
fi

# Check version.
version=$(mysql_version "${@}")
if test "${version}" != "18.0"; then
    printf 'This script upgrades 18.0 to 19.0. '
    printf 'Reported version is %s. Skipping upgrade.\n' "${version}"
    exit 0
fi

# Get the schema name from database argument. We need this to
# query information_schema for the right database.
for arg in "${@}"
do
    if ! printf '%s' "${arg}" | grep -Eq -- '^--'
    then
        schema="$arg"
        break
    fi
done

# Make sure we have the schema.
if [ -z "$schema" ]
then
    printf "Could not find database schema name in cmd line args: %s\n" "${*}"
    exit 255
fi

mysql "$@" <<EOF
-- This line starts the schema upgrade to version 19.0.
-- We have to play some games to make lease address
-- binary, primary key and retain its place as first
-- column.
-- Turn off Mariadb default/on-update for expire column
ALTER TABLE lease6 MODIFY expire timestamp NULL;
-- Store binary values for address in binaddr column
DROP INDEX lease6_by_binaddr ON lease6;
UPDATE lease6 set binaddr = inet6_aton(address);
ALTER TABLE lease6 DROP PRIMARY KEY, ADD PRIMARY KEY (binaddr);
-- Wipe existing address column contents so we can change data type
-- First remove the NULL constraint then set contents NULL
ALTER TABLE lease6 MODIFY COLUMN address VARCHAR(39) DEFAULT NULL;
UPDATE lease6 set address = NULL;
-- Change address data type
ALTER TABLE lease6 MODIFY COLUMN address BINARY(16);
-- Copy the binary values back to address
UPDATE lease6 set address = binaddr;
-- Restore address as primary key
ALTER TABLE lease6 DROP PRIMARY KEY, ADD PRIMARY KEY (address);
-- Drop binaddr column
ALTER TABLE lease6 DROP COLUMN binaddr;

-- Change data type of ipv6_reservations.address column.
-- Convert existing data via a temporary binary address column.
ALTER TABLE ipv6_reservations ADD COLUMN binaddr  BINARY(16);
UPDATE ipv6_reservations set binaddr = inet6_aton(address);
-- Wipe existing address column contents so we can change data type
-- First remove the NULL constraint then set contents NULL
ALTER TABLE ipv6_reservations MODIFY COLUMN address VARCHAR(39) DEFAULT NULL;
UPDATE ipv6_reservations set address = NULL;
ALTER TABLE ipv6_reservations MODIFY COLUMN address BINARY(16);
UPDATE ipv6_reservations set address = binaddr;
ALTER TABLE ipv6_reservations MODIFY COLUMN address BINARY(16) NOT NULL;
ALTER TABLE ipv6_reservations DROP COLUMN binaddr;

-- Convert binary lease6 address to text
DROP PROCEDURE IF EXISTS lease6DumpData;
DELIMITER $$
CREATE PROCEDURE lease6DumpData()
BEGIN
    SELECT
        INET6_NTOA(address),
        IFNULL(colonSeparatedHex(HEX(duid)), ''),
        valid_lifetime,
        UNIX_TIMESTAMP(expire),
        subnet_id,
        pref_lifetime,
        lease_type,
        iaid,
        prefix_len,
        fqdn_fwd,
        fqdn_rev,
        REPLACE(hostname, ',', '&#x2c'),
        IFNULL(colonSeparatedHex(HEX(hwaddr)), ''),
        state,
        REPLACE(IFNULL(user_context, ''), ',', '&#x2c'),
        hwtype,
        hwaddr_source,
        pool_id
    FROM lease6
    ORDER BY address;
END $$
DELIMITER ;

-- Drop and create lease6Upload stored procedure with conversion to
-- address to binary
DROP PROCEDURE IF EXISTS lease6Upload;
DELIMITER $$
CREATE PROCEDURE lease6Upload(
    IN address VARCHAR(39),
    IN duid VARCHAR(130),
    IN valid_lifetime INT UNSIGNED,
    IN expire BIGINT UNSIGNED,
    IN subnet_id INT UNSIGNED,
    IN pref_lifetime INT UNSIGNED,
    IN lease_type TINYINT,
    IN iaid INT UNSIGNED,
    IN prefix_len TINYINT UNSIGNED,
    IN fqdn_fwd TINYINT,
    IN fqdn_rev TINYINT,
    IN hostname VARCHAR(255),
    IN hwaddr VARCHAR(64),
    IN state INT UNSIGNED,
    IN user_context TEXT,
    IN hwtype SMALLINT,
    IN hwaddr_source INT UNSIGNED,
    IN pool_id INT UNSIGNED
)
BEGIN
    INSERT INTO lease6 (
        address,
        duid,
        valid_lifetime,
        expire,
        subnet_id,
        pref_lifetime,
        lease_type,
        iaid,
        prefix_len,
        fqdn_fwd,
        fqdn_rev,
        hostname,
        hwaddr,
        state,
        user_context,
        hwtype,
        hwaddr_source,
        pool_id
    ) VALUES (
        INET6_ATON(address),
        UNHEX(REPLACE(duid, ':', '')),
        valid_lifetime,
        FROM_UNIXTIME(expire),
        subnet_id,
        pref_lifetime,
        lease_type,
        iaid,
        prefix_len,
        fqdn_fwd,
        fqdn_rev,
        REPLACE(hostname, '&#x2c', ','),
        UNHEX(REPLACE(hwaddr, ':', '')),
        state,
        REPLACE(user_context, '&#x2c', ','),
        hwtype,
        hwaddr_source,
        pool_id
    );
END $$
DELIMITER ;

-- Update the schema version number.
UPDATE schema_version
    SET version = '19', minor = '0';

-- This line concludes the schema upgrade to version 19.0.
EOF
