+ const char *order;
+
+ char ed1[50];
+
+ db_lock(mdb);
+ if (item == -1) { /* find oldest volume */
+ /* Find oldest volume */
+ Mmsg(mdb->cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,"
+ "VolBytes,VolMounts,VolErrors,VolWrites,MaxVolBytes,VolCapacityBytes,"
+ "MediaType,VolStatus,PoolId,VolRetention,VolUseDuration,MaxVolJobs,"
+ "MaxVolFiles,Recycle,Slot,FirstWritten,LastWritten,InChanger,"
+ "EndFile,EndBlock,VolParts,LabelType,LabelDate,StorageId,"
+ "Enabled,LocationId,RecycleCount,InitialWrite,"
+ "ScratchPoolId,RecyclePoolId,VolReadTime,VolWriteTime "
+ "FROM Media WHERE PoolId=%s AND MediaType='%s' AND VolStatus IN ('Full',"
+ "'Recycle','Purged','Used','Append') AND Enabled=1 "
+ "ORDER BY LastWritten LIMIT 1",
+ edit_int64(mr->PoolId, ed1), mr->MediaType);
+ item = 1;
+ } else {
+ POOL_MEM changer(PM_FNAME);
+ /* Find next available volume */
+ if (InChanger) {
+ Mmsg(changer, "AND InChanger=1 AND StorageId=%s",
+ edit_int64(mr->StorageId, ed1));
+ }
+ if (strcmp(mr->VolStatus, "Recycle") == 0 ||
+ strcmp(mr->VolStatus, "Purged") == 0) {
+ order = "AND Recycle=1 ORDER BY LastWritten ASC,MediaId"; /* take oldest that can be recycled */
+ } else {
+ order = "ORDER BY LastWritten IS NULL,LastWritten DESC,MediaId"; /* take most recently written */
+ }
+ Mmsg(mdb->cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,"
+ "VolBytes,VolMounts,VolErrors,VolWrites,MaxVolBytes,VolCapacityBytes,"
+ "MediaType,VolStatus,PoolId,VolRetention,VolUseDuration,MaxVolJobs,"
+ "MaxVolFiles,Recycle,Slot,FirstWritten,LastWritten,InChanger,"
+ "EndFile,EndBlock,VolParts,LabelType,LabelDate,StorageId,"
+ "Enabled,LocationId,RecycleCount,InitialWrite,"
+ "ScratchPoolId,RecyclePoolId,VolReadTime,VolWriteTime "
+ "FROM Media WHERE PoolId=%s AND MediaType='%s' AND Enabled=1 "
+ "AND VolStatus='%s' "
+ "%s "
+ "%s LIMIT %d",
+ edit_int64(mr->PoolId, ed1), mr->MediaType,
+ mr->VolStatus, changer.c_str(), order, item);
+ }
+ Dmsg1(050, "fnextvol=%s\n", mdb->cmd);
+ if (!QUERY_DB(jcr, mdb, mdb->cmd)) {
+ db_unlock(mdb);