#!/command/with-contenv bash
# shellcheck shell=bash
# Do preparation tasks before starting the main services

set -o errexit -o nounset -o pipefail

function migrate_addon_config_dir() {
    local home_assistant_config_dir="/homeassistant"

    if ! mountpoint --quiet "${home_assistant_config_dir}"; then
        # Not running as a Home Assistant Add-on
        return 0
    fi

    local config_dir="/config"
    local new_config_file="${config_dir}/config.yml"
    local new_config_file_yaml="${new_config_file//.yml/.yaml}"
    if [[ -f "${new_config_file_yaml}" || -f "${new_config_file}" ]]; then
        # Already migrated
        return 0
    fi
    unset new_config_file new_config_file_yaml

    local old_config_file="${home_assistant_config_dir}/frigate.yml"
    local old_config_file_yaml="${old_config_file//.yml/.yaml}"
    local new_config_file="${config_dir}/config.yml"
    if [[ -f "${old_config_file}" ]]; then
        :
    elif [[ -f "${old_config_file_yaml}" ]]; then
        old_config_file="${old_config_file_yaml}"
    else
        # Nothing to migrate
        return 0
    fi
    unset old_config_file_yaml

    local db_path
    db_path=$(yq -r '.database.path' "${old_config_file}")
    if [[ "${db_path}" == "null" ]]; then
        db_path="${config_dir}/frigate.db"
    fi
    if [[ "${db_path}" == "${config_dir}/"* ]]; then
        # replace /config/ prefix with /homeassistant/
        local old_db_path="${home_assistant_config_dir}/${db_path:8}"

        if [[ -f "${old_db_path}" ]]; then
            local new_db_dir
            new_db_dir="$(dirname "${db_path}")"
            echo "[INFO] Migrating database from '${old_db_path}' to '${new_db_dir}' dir..."
            mkdir -vp "${new_db_dir}"
            mv -vf "${old_db_path}"* "${new_db_dir}"
        fi
    fi

    local model_path
    model_path=$(yq -r '.model.path' "${old_config_file}")
    if [[ "${model_path}" == "${config_dir}/"* ]]; then
        # replace /config/ prefix with /homeassistant/
        local old_model_path="${home_assistant_config_dir}/${model_path:8}"

        if [[ -f "${old_model_path}" ]]; then
            local new_model_dir
            new_model_dir="$(dirname "${model_path}")"
            echo "[INFO] Migrating model from '${old_model_path}' to '${model_path}'..."
            mkdir -vp "${new_model_dir}"
            mv -vf "${old_model_path}" "${model_path}"
        fi
    fi

    local ffmpeg_path
    ffmpeg_path=$(yq -r '.ffmpeg.path' "${old_config_file}")
    if [[ "${ffmpeg_path}" == "${config_dir}/"* ]]; then
        # replace /config/ prefix with /homeassistant/
        local old_ffmpeg_path="${home_assistant_config_dir}/${ffmpeg_path:8}"

        if [[ -d "${old_ffmpeg_path}" ]]; then
            local new_ffmpeg_dir
            new_ffmpeg_dir="$(dirname "${ffmpeg_path}")"
            echo "[INFO] Migrating ffmpeg from '${old_ffmpeg_path}' to '${ffmpeg_path}'..."
            mkdir -vp "${new_ffmpeg_dir}"
            mv -vf "${old_ffmpeg_path}" "${ffmpeg_path}"
        fi
    fi

    local old_model_cache_path="${home_assistant_config_dir}/model_cache"
    if [[ -d "${old_model_cache_path}" ]]; then
        echo "[INFO] Migrating '${old_model_cache_path}' to '${config_dir}'..."
        mv -f "${old_model_cache_path}" "${config_dir}"
    fi

    echo "[INFO] Migrating other files from '${home_assistant_config_dir}' to '${config_dir}'..."
    local file
    for file in .exports .jwt_secret .timeline .vacuum go2rtc; do
        file="${home_assistant_config_dir}/${file}"
        if [[ -f "${file}" ]]; then
            mv -vf "${file}" "${config_dir}"
        fi
    done

    echo "[INFO] Migrating config file from '${old_config_file}' to '${new_config_file}'..."
    mv -vf "${old_config_file}" "${new_config_file}"

    echo "[INFO] Migration from Home Assistant config dir to Add-on config dir completed."
}

function migrate_db_from_media_to_config() {
    # Find config file in yml or yaml, but prefer yml
    local config_file="${CONFIG_FILE:-"/config/config.yml"}"
    local config_file_yaml="${config_file//.yml/.yaml}"
    if [[ -f "${config_file}" ]]; then
        :
    elif [[ -f "${config_file_yaml}" ]]; then
        config_file="${config_file_yaml}"
    else
        # Frigate will create the config file on startup
        return 0
    fi
    unset config_file_yaml

    local user_db_path
    user_db_path=$(yq -r '.database.path' "${config_file}")
    if [[ "${user_db_path}" == "null" ]]; then
        local old_db_path="/media/frigate/frigate.db"
        local new_db_dir="/config"
        if [[ -f "${old_db_path}" ]]; then
            if mountpoint --quiet "${new_db_dir}"; then
                # /config is a mount point, move the db
                echo "[INFO] Migrating database from '${old_db_path}' to '${new_db_dir}' dir..."
                # Move all files that starts with frigate.db to the new directory
                mv -vf "${old_db_path}"* "${new_db_dir}"
            else
                echo "[ERROR] Trying to migrate the database path from '${old_db_path}' to '${new_db_dir}' dir, but '${new_db_dir}' is not a mountpoint, please mount the '${new_db_dir}' dir"
                return 1
            fi
        fi
    fi
}

echo "[INFO] Preparing Frigate..."

migrate_addon_config_dir
migrate_db_from_media_to_config
