#!/bin/bash

mountid="${1}"
user="${2}"
container="${3}"
if [[ -z ${mountid} ]] || [[ -z ${user} ]]; then
    echo "We need a valid mount id and user to proceed"
    echo "Usage: ${0} <mountid> <user> [<container>]"
    exit
fi

if [[ -z ${container} ]]; then
    container="nextcloud_app_1"
fi

occ="/usr/local/bin/occ ${container}"
function get_config {
  ${occ} files_external:config ${mountid} ${1} | tr -d '\n\t\r'
}

echo "Gathering information, hang tight."

echo -n "."
bucket="$(get_config bucket)"
echo -n "."
hostname="$(get_config hostname)"
echo -n "."
key="$(get_config key)"
echo -n "."
region="$(get_config region)"
echo -n "."
secret="$(get_config secret)"
jsonfile="/tmp/${user}-user-bucket.json"
mount_point="${user/@/-}"
mount_point="${mount_point/./-}-user-bucket"

echo "This will remount the user bucket with mountid ${mountid} for ${user} as project bucket with mountpoint ${mount_point}."
read -r -p "Press enter to continue"

echo '
[
    {
        "mount_point": "\/'${mount_point}'",
        "storage": "\\OCA\\Files_External\\Lib\\Storage\\AmazonS3",
        "authentication_type": "amazons3::accesskey",
        "configuration": {
            "bucket": "'${bucket}'",
            "hostname": "'${hostname}'",
            "key": "'${key}'",
            "legacy_auth": false,
            "port": "443",
            "region": "'${region}'",
            "secret": "'${secret}'",
            "storageClass": "",
            "useMultipartCopy": false,
            "use_path_style": true,
            "use_ssl": true
        },
        "options": {
            "encrypt": true,
            "previews": true,
            "enable_sharing": true,
            "filesystem_check_changes": 0,
            "encoding_compatibility": false,
            "readonly": false
        },
        "applicable_users": [
        ],
        "applicable_groups": ["admin"]
    }
]
' > "${jsonfile}"


docker cp ${jsonfile} ${container}:/${jsonfile}
${occ} files_external:import /${jsonfile}
docker exec ${container} rm /${jsonfile}
rm ${jsonfile}
${occ} files_external:delete ${mountid}