#!/bin/bash
#which cc 1>/dev/null 2>/dev/null || exit 1
Me=$(true_path $0)
PATH=${PATH}:${Me%/*}/${BASE_ARCH}
[[ "$1" != Force ]] && which link_files_in_dir 2>/dev/null >/dev/null && exit 0
cd $TMPDIR/bin || exit 1
[[ -x link_files_in_dir ]] && exit 0
  cat <<EOT >link_files_in_dir.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>

#define MAX_ENTRIES 200

usage(char *str) {
  fprintf(stderr,"Usage: %s [--lib] [maxdirsize] path_to_scan [path_to_link_into]\n",str);
  exit(1);
}

main(int argc, char **argv){

int entries=0;
int file_count = 0;
DIR * dirp;
struct dirent * entry;
char old_path[4096], new_path[4096];
int status;
char *so_string=".so";
int look_for_so=0;
char *my_name = argv[0];
int max_entries;

if(argc<2)  usage(my_name);  /* not enough arguments */
if(strcmp("--help",argv[1]) == 0 || strcmp("-h",argv[1]) == 0 ) {
  usage(my_name);
}

if(argc<2)  usage(my_name);  /* not enough arguments */
if(strcmp("--lib",argv[1]) == 0) {  /* library path mode, look for .so */
  argc--;
  argv++;
  look_for_so=1;
}

max_entries = atoi(argv[1]);
if(max_entries > 0) {   /* maximum allowable entries in directory in order to cache */
  argc--;
  argv++;
}else{
  max_entries = MAX_ENTRIES;
}

if(argc<2)  usage(my_name);

/* fprintf(stderr,"Scanning %s\n",argv[1]);   */
dirp = opendir(argv[1]);
if(dirp == NULL) { /* error while trying to open directory */
  /* fprintf(stderr,"ERROR opening %s\n",argv[1]); */
  exit(3);
}

while ((entry = readdir(dirp)) != NULL) {
  entries++;
  if(entries > max_entries){
  /*  fprintf(stderr,"more than %d entries found in %s, EXITING\n",max_entries,argv[1]);   */
    closedir(dirp);
    exit(2);  /* too many entries */
  }
}

if(argc == 2) {  /* we are only checking the number of entries */
  closedir(dirp);
  exit(0);
}
if(argc!=3) usage(my_name);  /* too many arguments */

rewinddir(dirp);
while ((entry = readdir(dirp)) != NULL) {
    if(strcmp("." ,entry->d_name) == 0) continue;
    if(strcmp("..",entry->d_name) == 0) continue;
#ifdef __linux
    if (entry->d_type == DT_DIR) { /* If the entry is a directory (linux only feature) */
      continue;
    }
#endif
    snprintf(old_path,sizeof(old_path),"%s/%s",argv[1],entry->d_name);
    snprintf(new_path,sizeof(new_path),"%s/%s",argv[2],entry->d_name);

/*    if(NULL != strstr(entry->d_name,so_string)) fprintf(stderr,".so file located\n");   */
    if(look_for_so & (NULL == strstr(entry->d_name,so_string))) continue;

    status = symlink(old_path,new_path);
/*    fprintf(stderr,"%d ln -s %s %s\n",status,old_path,new_path);   */
    if(status==0)file_count++;
}
/*fprintf(stderr,"Linked %d files from %s into %s\n",file_count,argv[1],argv[2]);   */
closedir(dirp);
exit(0);
}
EOT
make link_files_in_dir
rm -f link_files_in_dir.c
