/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#+
#+     Internet Radio Automation & Encoding Toolkit
#+
#+     Copyright (C) 2018, 2019, 2020, 2021, 2022 by Kevin C. O'Kane
#+
#+     Kevin C. O'Kane
#+     kc.okane@gmail.com
#+     https://www.cs.uni.edu/~okane
#+     https://threadsafebooks.com/
#+
#+ This program is free software; you can redistribute it and/or modify
#+ it under the terms of the GNU General Public License as published by
#+ the Free Software Foundation; either version 2 of the License, or
#+ (at your option) any later version.
#+
#+ This program is distributed in the hope that it will be useful,
#+ but WITHOUT ANY WARRANTY; without even the implied warranty of
#+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#+ GNU General Public License for more details.
#+
#+ You should have received a copy of the GNU General Public License
#+ along with this program; if not, write to the Free Software
#+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#+
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

//	Oct 25, 2022

//#include <stdio.h>

#include "includes.h"
#include "common-externs.h"

int	smbParse(char * vlcRef, char *playThis) {

	char fileRef[4096] = "";
	char server[1024] = "";
	char share[1024] = "";
	char smbRef[4096] = "";
	char mediaRef[2048] = "";
	char tmp[1024];
	int i;

	strcpy(fileRef, playThis);

	for (i = 6; fileRef[i] != 0; i++)
		if (fileRef[i] == '/') break;

	if (fileRef[i] == 0) {
		printf("*** smb server ref error\n");
		return 0;
		} // fail

	if (fileRef[i+i] == 0) {
		printf("*** smb share ref error\n");
		return 0;
		} // fail

	fileRef[i] = 0;

	strcpy(server, &fileRef[6]);

	strcpy(share, &fileRef[i+1]);

	for (i = 0; share[i] != 0; i++)
		if (share[i] == '/') break;

	if (share[i] == 0) {
		printf("*** smb file ref error\n");
		return 0;
		} // fail

	share[i] = 0; // end of share name

	if (share[i+1] == 0) return 0; //fail

	strcpy(mediaRef, &share[i+1]);

	strcpy(smbRef, "smb-share:server=");
	strcat(smbRef, server);
	strcat(smbRef, ",share=");
	strcat(smbRef, share);

	FILE *f = popen("ls /run/user/1000/gvfs", "r");

	if (f == NULL) {
		printf("*** smb /run/user link not found.\n");
		return 0; // fail
		}

	int flg = 0;
	while( fgets(tmp, 1024, f) != NULL) {
		tmp[strlen(tmp)-1] = 0; // newline
		if (strcmp(tmp, smbRef) == 0) {
			flg = 1; // found it
			printf("*** Found: %s\n", smbRef);
			}
		}

	fclose(f);

	if (!flg) {
		printf("*** smb /run/user link not found.\n");
		return 0; // fail
		}

	strcpy(vlcRef, "/run/user/1000/gvfs/smb-share:server=");
	strcat(vlcRef, server);
	strcat(vlcRef, ",share=");
	strcat(vlcRef, share);
	strcat(vlcRef, "/");
	strcat(vlcRef, mediaRef);

	for (i = strlen(vlcRef) - 1; i > 0; i--)
		if (vlcRef[i] == ' ') vlcRef[i] = 0;
		else break;

	return 1;
	}
