#!/bin/sh

# Copy file from specified location or from policy share
adp_copy_file() 
{
	location="$1"; shift
	target_file="$1"; shift

	# Make path for target_file
	target_dir="$(dirname "$target_file")"
	if [ ! -e "$target_dir" ]; then
		mkdir -p "$target_dir"
	fi

	if [[ "$location" =~ ^\/.*|^\$.*  ]]; then
		install "$location" "$target_file"
	elif [[ "$location" =~ ^ftp.*|^http.*  ]]; then
		curl -o "$target_file" "$location"
	elif [[ "$location" =~ ^smb.*  ]]; then
		# Find file, server and folder in location
		source_file="$(basename "$location")"
		location="$(dirname "$location")"
		location=${location#smb:}
		folder=${location#//*/*/}

		if [[ -z "$folder" || "$folder" = "$location" ]]; then
			share="$location"
			cd_folder=""
		else
			share=${location//$folder}
			cd_folder="cd $folder; "
		fi

		cd /tmp
		smbclient -N -k $share -c "prompt OFF; $cd_folder get $source_file"
		mv $source_file $target_file
	else
		echo "URL is invalid"
		exit 1
	fi
}
