#!/bin/bash

# Copyright 2024 Browsolate Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


#set -x
# Function to base64 encode the username:password for Basic Auth
create_auth_header() {
  local username="b8admin"
  local password="$1"

  # Encode the username and password in base64
  echo -n "$username:$password" | base64
}

# Function to call the /encrypt endpoint on the API
encrypt_via_api() {
  local key_name="$1"
  local json_data="$2"
  local api_url="${base_url}:5443/encrypt"  # Append port 5443 to base_url
  local auth_header=$(create_auth_header "$password")

  # Wrap the json_data into the expected API request structure, stringify the data
  request_body=$(jq -c -n --arg keyName "$key_name" --argjson data "$json_data" '{
    keyName: $keyName,
    data: $data
  }')

  # Call the encryption API using curl (verbose mode)
  encrypted_data=$(curl -s $insecure -X POST "$api_url" \
    -H "Authorization: Basic $auth_header" \
    -H "Content-Type: application/json" \
    -d "$request_body" | jq -r .encryptedData)

  # Check if the encryption was successful
  if [[ "$encrypted_data" == "null" || -z "$encrypted_data" ]]; then
    echo "Error: Failed to encrypt data."
    exit 1
  fi

  echo "$encrypted_data"
}

# Initialize variables
base_url=""
navigate_url=""
key_name="default"  # Default key_name is 'default'
password=""
insecure=""

# Usage function to display help
usage() {
    echo "Usage: $0 [-b base_url] [-u navigate_url] [-k key_name] [-p password] [-h]"
    echo "  -b browsolate_url URL of Browsolate host."
    echo "  -u navigate_url   URL to navigate to."
    echo "  -k key_name       Key name for encryption/decryption (default: 'default')."
    echo "  -p password       Password for basic authentication."
    echo "  -i                Allow insecure connections"
    echo "  -h                Display this help message."
    exit 1
}

# Parse options using getopts
while getopts "b:u:k:p:ih" opt; do
  case $opt in
    b)
      base_url="$OPTARG"
      ;;
    u)
      navigate_url="$OPTARG"
      ;;
    k)
      key_name="$OPTARG"
      ;;
    p)
      password="$OPTARG"
      ;;
    i)
      insecure="--insecure"
      ;;
    h)
      usage
      ;;
    *)
      usage
      ;;
  esac
done

# Ensure base_url, navigate_url, and password are provided
if [[ -z "$base_url" || -z "$navigate_url" || -z "$password" ]]; then
    usage
fi

# Provided JSON to encrypt (single-line JSON object with the URL passed from the command line)
json_data=$(jq -c -n --arg url "$navigate_url" '{
    clipboardRead: true,
    clipboardWrite: true,
    readOnly: false,
    navigation: true,
    urlEditable: false,
    sessionLifetime: 300,
    sessionExtensionAllowed: false,
    sessionExtensionTime: 30,
    screenWidth: 1024,
    screenHeight: 768,
    mobileAutoSize: true,
    userAgent: "",
    customRequestHeaders: {},
    debugMode: false,
    linkId: "",
    linkExpiry: -1,
    logDirectUrlNavigation: false,
    logIndirectUrlNavigation: false,
    url: $url
}')

# Encrypt the JSON data via API
encrypted_data=$(encrypt_via_api "$key_name" "$json_data")

# Construct the final URL with /viewer.html, key_name as keyId, and the encrypted data
final_url="${base_url}/viewer.html?&keyId=$key_name&b8data=$encrypted_data"

# Output the final URL
echo "$final_url"
