#!/bin/bash

if [ $# -ne 1 ]; then
  echo "Usage: $0 path/to/your/file.ext"
  exit 1
fi

CONFIG_FILE="/var/lib/openvpn-server/openssl/.nextcloudupload.conf"

if [ ! -f "$CONFIG_FILE" ]; then
  echo "Configuration file not found: $CONFIG_FILE"
  exit 1
fi

# Load the configuration from the file
source "$CONFIG_FILE"

# Set the file you want to upload
FILE_TO_UPLOAD=$1

# Generate a random 8 character string for the new folder name
NEW_FOLDER_NAME=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 8)

# Create the vpnbuilds folder if it doesn't exist
curl -s -u "$NEXTCLOUD_USER:$NEXTCLOUD_TOKEN" -X MKCOL "$NEXTCLOUD_URL/remote.php/dav/files/$NEXTCLOUD_USER/vpnbuilds" >/dev/null

# Create the new subfolder inside vpnbuilds
curl -s -u "$NEXTCLOUD_USER:$NEXTCLOUD_TOKEN" -X MKCOL "$NEXTCLOUD_URL/remote.php/dav/files/$NEXTCLOUD_USER/vpnbuilds/$NEW_FOLDER_NAME" >/dev/null

# Upload the file to the new subfolder
curl -s -u "$NEXTCLOUD_USER:$NEXTCLOUD_TOKEN" -T "$FILE_TO_UPLOAD" "$NEXTCLOUD_URL/remote.php/dav/files/$NEXTCLOUD_USER/vpnbuilds/$NEW_FOLDER_NAME/$(basename $FILE_TO_UPLOAD)" >/dev/null

# Create a share for the folder
SHARE_RESPONSE=$(curl -s -u "$NEXTCLOUD_USER:$NEXTCLOUD_TOKEN" -H "OCS-APIRequest: true" -X POST -d "path=/vpnbuilds/$NEW_FOLDER_NAME&shareType=3" "$NEXTCLOUD_URL/ocs/v1.php/apps/files_sharing/api/v1/shares")

# Get the share ID
SHARE_ID=$(echo "$SHARE_RESPONSE" | grep -oP '(?<=<id>).*(?=</id>)')

# Generate a random 18 character string for the share password
PASSWORD=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 18)

# Set the expiration date for the share link
EXPIRY_DATE=$(date -u -d "7 days" +%Y-%m-%d)

curl -s -u "$NEXTCLOUD_USER:$NEXTCLOUD_TOKEN" -H "OCS-APIRequest: true" -X PUT -d "password=$PASSWORD&expireDate=$EXPIRY_DATE" "$NEXTCLOUD_URL/ocs/v1.php/apps/files_sharing/api/v1/shares/$SHARE_ID" >/dev/null

# Get the share link
SHARE_LINK=$(echo "$SHARE_RESPONSE" | grep -oP '(?<=<url>).*(?=</url>)')

echo "Share link: $SHARE_LINK"
echo "Share password: $PASSWORD"
echo "Expiration date: $EXPIRY_DATE"

