-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathx2y
131 lines (114 loc) · 2.27 KB
/
x2y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#!/usr/bin/env bash
the_name="x2y"
print_usage() {
echo "Usage: $the_name [(-f | --format) <format>] <file>[:<format>] ..."
echo
echo "OPTIONS"
echo " -h, --help Display this help message"
echo " -f <format>, --format <format> Set default output format"
echo
echo "EXAMPLES"
echo " $the_name --format mp3 *.opus"
echo " $the_name foo:pdf bar:png"
}
convert_with_ffmpeg() {
ffmpeg -i "$1" "$2"
}
convert_with_imagemagick() {
convert "$1" "$2"
}
convert_with_pdftoppm() {
input_file="$1"
output_file="$2"
output_format=${output_file##*.}
output_base="$(basename "$output_file" ."$output_format")"
case $output_format in
png)
command="pdftoppm -png"
;;
jpeg | jpg)
command="pdftoppm -jpeg"
;;
tiff)
command="pdftoppm -tiff"
;;
*)
echo "Error: Output format must be PNG/JPEG/TIFF for PDF conversion"
exit 1
;;
esac
"$command" "$input_file" "$output_base"
}
# Transform long options to short ones for `getopts`
for arg in "$@"; do
shift
case "$arg" in
"--help")
set -- "$@" "-h"
;;
"--format")
set -- "$@" "-f"
;;
*)
set -- "$@" "$arg"
;;
esac
done
format=
while getopts ":hf:" opt; do
case ${opt} in
h)
print_usage
exit 0
;;
f)
format=$OPTARG
;;
*)
echo "Invalid option: $opt"
print_usage
exit 2
;;
esac
done
# Remove processed options
shift $((OPTIND - 1))
if [ $# -eq 0 ]; then
print_usage
exit 1
fi
for arg in "$@"; do
if [[ -z $format ]]; then
if [[ $arg == *:* ]]; then
input_file="${arg%:*}"
output_format="${arg#*:}"
output_file="${input_file%.*}.$output_format"
else
print_usage
exit 2
fi
else
input_file="$arg"
output_file="${input_file%.*}.$format"
fi
if [ ! -f "$input_file" ]; then
echo "Error: Input file '$input_file' does not exist"
exit 1
fi
mime_type="$(file --brief --mime-type "$input_file")"
case "$mime_type" in
audio/* | video/*)
convert_cmd=convert_with_ffmpeg
;;
image/*)
convert_cmd=convert_with_imagemagick
;;
application/pdf)
convert_cmd=convert_with_pdftoppm
;;
*)
echo "Error: Unsupported MIME type '$mime_type'"
;;
esac
$convert_cmd "$input_file" "$output_file"
done