/*# truncate.c - truncate file at a given point, may be relative to file's end
###              and can be specified in CDDA seconds
### Copyright (C) 1999  Arne Zellentin <arne@unix-ag.org>

### 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

### see http://www.home.unix-ag.org/arne/scripToys/ for details.
#
# usage: truncate <arg> <file1> [<, ...,> <filen>]
# arg can be a number, if negative count from end of file,
# if followed by 's' CDDA seconds are used,
# if followed by 'S' CDDA seconds are used and file(s) are only truncated
#    if the part to cut off contains only zeros */


#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

void main(int argc, char **argv)
{
  struct stat buf;
  char arr[2];
  int f;
  int i;
  int secure=0;
  int yestruncateme;
  int truncate_arg;
  int truncate_to;

  if(argc<3) {
    printf("usage: %s <count> file(s)\n",argv[0]);
    exit(1);
  }
  if(argv[1][strlen(argv[1])-1]=='S') {
    secure=1;
    argv[1][strlen(argv[1])-1]='s';
  }
  if(argv[1][strlen(argv[1])-1]=='s') {
    argv[1][strlen(argv[1])-1]=0;
    truncate_arg=atoi(argv[1])*75*2352;
/* printf("arg: %i\n",truncate_arg); */
  }
    
  for(i=2; i<argc;i++) {
    yestruncateme=1;
    if(truncate_arg<0)
      if(stat(argv[i],&buf))
        perror(argv[0]);
      else
        truncate_to=buf.st_size+truncate_arg;
    else
      truncate_to=truncate_arg;
    if(secure) {
      f=open(argv[i],O_RDONLY);
      lseek(f,truncate_to,SEEK_SET);
      while(read(f,arr,1))
        if(arr[0]!=0)
          yestruncateme=0;
      close(f);
    }

/* printf("%s to %i\n",argv[i],truncate_to); */
    if(!secure || yestruncateme) {
      if(truncate(argv[i],truncate_to))
         perror(argv[0]);
    }
    else
      printf("%s: data to truncate is not all zero, skipping...\n",argv[i]);
  }
}

